It gives the following error:
Property 'name' does not exist on type NonNullable
.
The problem is, that the TypeScript compiler does not understand the subtle type narrowing here and throws a compile-time error as stated here (though, I am not 100% sure about how helpful this blog post is for you).
Removing undefined
from Foo
works:
type Foo = { name: string }
function fooWorks<T extends Foo>(input: T) {
return input?.name
}
function fooErrors<T extends Foo>(input: Readonly<T>) {
return input?.name
}
Or you can add the NonNullable
type excluding null
and undefined
from T
, which results in input
being { name: string }
:
type Foo = { name: string } | undefined
function fooWorks<T extends Foo>(input: T) {
return input?.name
}
function fooErrors<T extends Foo>(input: Readonly<NonNullable<T>>) {
return input.name
}