简体   繁体   中英

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

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

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

{
    name:undefined;
    age:undefined;
}

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM