Ram Somani
Ram Somani

Reputation: 241

Typescript giving Type '"Test"' is not assignable to type 'undefined'

I have a simple object having two fields name and age, initially those are defined as undefined and later in the code the value will get assigined

const s={
    name:undefined,
    age:undefined
}
s.name="Test" //error

when I am trying to assign any value to my attributes it gives me typescript error

Type '"Test"' is not assignable to type 'undefined'.

Can anyone explain why I am getting this error in typescript and how to fix it

Upvotes: 2

Views: 839

Answers (2)

spender
spender

Reputation: 120400

If you look at the inferred type of s you can see that it is

{
    name:undefined;
    age:undefined;
}

enter image description here

TypeScript can't infer that any other type might be allowed here because you didn't supply that info.

Create a type:

interface Person{
    name: string | undefined;
    age: number | undefined;
}

then declare s with this type:

const s:Person = {
    name: undefined;
    age: undefined;
}

Playground Link

Upvotes: 1

hendra
hendra

Reputation: 2651

You did not explicitly define a type for s, so the compiler tries to infer one, based on the provided values.

The inferred type of s is:

{
  name: undefined;
  age: undefined;
}

You have set an explicit type like so:

type User = {
  name: string | undefined;
  age: number | undefined;
};

const s: User = {
    name: undefined,
    age: undefined
};
s.name = "Test"; //should work

Upvotes: 2

Related Questions