TypeScript: Type 'any' is not assignable to type 'never' with boolean in interface in TS 3.5
TypeScript Version: 3.5.1
Search Terms:
- Type ‘any’ is not assignable to type ‘never’
Code
interface T {
str: string;
bool: boolean;
}
const initState: T = {
str: 'date',
bool: true,
};
let k: keyof T;
initState[k] = 'test' as any;
// ~~~~~~~~~~~~ Type 'any' is not assignable to type 'never'.ts(2322)
This seems to happen specifically with boolean
properties. If I get rid of the boolean
-valued property from the interface it works fine. If I have a larger interface and select non-boolean
properties, it also works fine. But boolean
and another type produces this error.
This error happens with TS 3.5 but not 3.4 (see playground link).
Expected behavior:
No error.
Actual behavior:
Type 'any' is not assignable to type 'never'
Playground Link: link
Related Issues:
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 18
- Comments: 15 (9 by maintainers)
Links to this issue
Commits related to this issue
- chore(typescript): update to typescript 3.7.x Update eslint, eslint-config-prettier, eslint-loader, @typescript-eslint/eslint-plugin, @typescript-eslint/parser This adds lots of `any` usage, which is... — committed to christopherthielen/deck by christopherthielen 5 years ago
- chore(typescript): update to typescript 3.7.x Update eslint, eslint-config-prettier, eslint-loader, @typescript-eslint/eslint-plugin, @typescript-eslint/parser This adds lots of `any` usage, which is... — committed to christopherthielen/deck by christopherthielen 5 years ago
- passing tests with a workaround for typescript bug https://github.com/microsoft/TypeScript/issues/31663 — committed to architect-team/architect-cli by ryan-cahill 5 years ago
@KeithHenry if you put the
as any
after the property access, TypeScript will check thatk
is a valid key. This is more similar to what TS did before 3.5.This has caused a very large number of errors for us with insufficient guidance of how to fix (from the release notes)…
OK, so we have large numbers of a pattern that looks like (from the OP):
And these all fail because we have lots of
boolean
properties, and so TypeScript thinks the type ofinitState[k]
isnever
(surely that’s wrong?)Is the solution:
boolean
from all interfaces? What should be used instead? Isboolean
deprecated now?k
isboolean
that then gates it out of theinitState[k]
check?keyof
to just deal withany
instead and lose type checking? Something like…@KeithHenry the gist of the breaking change was that you never had type safety in the assignment to begin with. If you want the old behavior, you can put an
as any
around theinitState[k]
:Alternatively, you can construct a narrower type than
keyof T
which consists of only those keys whose values are assignable to boolean. You can do this quite generally with a conditional type:@Zarepheth
Try this:
(I added a
-?
in the mapped type to remove the optional-ness of the properties.)