This is similar to #40796374 but that is around types, while I am using interfaces.
Given the code below:
interface Foo {
name: string;
}
function go() {
let instance: Foo | null = null;
let mutator = () => {
instance = {
name: 'string'
};
};
mutator();
if (instance == null) {
console.log('Instance is null or undefined');
} else {
console.log(instance.name);
}
}
I have an error saying 'Property 'name' does not exist on type 'never'.
I don't understand how instance could ever be a 'never'. Can anyone shed some light on this?
Thanks in advance.
Because you are assigning
instance
tonull
. The compiler infers that it can never be anything other thannull
. So it assumes that the else block should never be executed soinstance
is typed asnever
in the else block.Now if you don't declare it as the literal value
null
, and get it by any other means (ex:let instance: Foo | null = getFoo();
), you will see thatinstance
will benull
inside the if block andFoo
inside the else block.Never type documentation: https://www.typescriptlang.org/docs/handbook/basic-types.html#never
Edit:
The issue in the updated example is actually an open issue with the compiler. See:
https://github.com/Microsoft/TypeScript/issues/11498 https://github.com/Microsoft/TypeScript/issues/12176