-
Notifications
You must be signed in to change notification settings - Fork 12.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Incorrectly sets type to "never" #32375
Comments
I think this is caused by #30769, and I would start there to read up on the motivation for the changes. |
Why this happens: the compiler knows one of several properties will be accessed, but not which one; so in order to maintain type safety it only allows you to write using that key if all the types selected overlap. This is working as designed and not a bug. |
I'm still confused about why this isn't a bug. How else are you meant to write this without getting any errors? What changes would I need to make to get this to work? |
It's not a bug because prior to TS 3.5, the error below wasn't caught: interface Foo {
foo: string;
bar: boolean;
}
const foo: Foo = { foo: "foo", bar: true };
function setIt(obj: Foo, key: keyof Foo, value: Foo[keyof Foo]) {
obj[key] = value; // in 3.5, an error; 3.4 or earlier, no error
}
setIt(foo, "bar", "oops!");
console.log(foo.bar); // bar is typed as boolean but now contains a string The loophole is that |
The example is very strange as written. Why is Without the generic function, you're telling TS that |
Thanks @nattthebear. I did it this way as
seemed to me that it was the same as leaving the generics as default, since Anyway, your solution works. Thanks for the help! |
Yeah, it doesn't, you have to pass the type parameters through manually. That's why you got the |
TypeScript Version: 3.5.3
Search Terms: type is not assignable to type 'never', keyof, generic
Code
Expected behavior:
No issue. Type
formState[form].fields[field][key]
correctly gets the type asconst key: "isInvalid" | "isValid" | "labelWidth" | "showPassword" | "value"
andvalue
correctly gets the type asconst value: string | number | boolean | undefined
. Nowhere in there isnever
defined as a possible type.Actual behavior:
Playground Link: Link to playground
The text was updated successfully, but these errors were encountered: