plantain-00 / type-coverage

A CLI tool to check type coverage for typescript code
MIT License
1.21k stars 43 forks source link

Deal with type guards in strict mode #61

Closed darky closed 3 years ago

darky commented 3 years ago

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 of as is forbidden.

plantain-00 commented 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

darky commented 3 years ago

return (pet as Fish).foo?.bar !== undefined; is safe.

plantain-00 commented 3 years ago

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
}
darky commented 3 years ago

Workaround is use something like lodash get