Typescript: Narrowing down type bypasses type checker

Created on 27 Mar 2019  ·  5Comments  ·  Source: microsoft/TypeScript

TypeScript 3.3.1

This imho should not be allowed:

const foo = { foo: false } as { foo: boolean, bar: boolean };

As it bypasses the type checker from doing its job. I now have basically introduced a type with undefined as foo.bar even though it should be boolean | undefined.

If someone wants this type by all means, it is still possible by using any.

const foo = { foo: false } as any as { foo: boolean, bar: boolean };

That way at least one can find hacks easily.

I would like to see a warning for this, possibly via some kind of new strict rule ideally.

I actually use as or <> a lot in my code to get IntelliSense for an object literal I am writing and ensuring the values I give it are correct, but now I am not so sure anymore.

Working as Intended

Most helpful comment

It would be great if that was easy to use like the as operator, e.g. something like

const foo = { foo: false } is { foo: boolean, bar: boolean };

would report as error.

All 5 comments

Type assertions have always been unsound because they let you move in the inverse direction of assignability. If you want type-checking then you need to write:

const foo: { foo: boolean, bar?: boolean } = { foo: false };

If you explicitly want expression level syntax then I think you're looking for #7481

It would be great if that was easy to use like the as operator, e.g. something like

const foo = { foo: false } is { foo: boolean, bar: boolean };

would report as error.

See #7481

Are you aware that you can annotate variables?

const foo: { foo: boolean, bar: boolean } = { foo: false };

@RyanCavanaugh sure that is a workaround but I often end up with a long expression (possibly ternary operators) where I might have multiple types on the way and I typically prefer to declare their types on the way and not all upfront for better readability.

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Was this page helpful?
0 / 5 - 0 ratings