Closed darky closed 3 years ago
I think it's not safe, for example:
type Fish = { foo: { bar: number } };
type Bird = { baz: number };
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).foo.bar !== undefined;
}
isFish({ baz: 1 })
The error is: Cannot read property 'bar' of undefined
return (pet as Fish).foo?.bar !== undefined;
is safe.
I mean pet as Fish
is not safe.
not safe
does not means always invalid
, for example:
function foo(bar: any) { // I found `bar` is any(not safe), so I report it
return bar.baz // `foo` may or may not has `baz`, so it is not safe
}
Workaround is use something like lodash get
Version(if relevant): 2.10.0
https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
In TypeScript documentation for using user defined type guards need to use
as
for correct property check. How to implement user defined type guards with type-coverage with strict mode? Use ofas
is forbidden.