score:2

Accepted answer

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

score:1

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


Related Query

More Query from same tag