You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm trying to write a function to set a field in an object using a string literal type. I can write the signature for it, but I can't write the body. A simplified version of it looks like this:
functionfoo1<Nextendsstring>(key: N): {[keyinN]: string}{return{[key]: 'foo'};// ~~~~~~~~~~~~~~~~~~~~~~~~// Type '{ [x: string]: string }' is not assignable to type '{[key in N: string}'}functionfoo2<Nextendsstring>(key: N): {[keyinN]: string}{return{[key]: 'foo'}asany;// Cast away the error}constx=foo2('henk');// x :: { henk: string } as expected
I imagine this has something to do with the keys of an object literal being declared to be string and the stronger type N extends string getting dropped on the floor?
But the code feels like it is correct and it feels like the type system should be able to see that.
Checklist
My suggestion meets these guidelines:
This wouldn't be a breaking change in existing TypeScript/JavaScript code
This wouldn't change the runtime behavior of existing JavaScript code
This could be implemented without emitting different JS based on the types of the expressions
This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
Keys in mapped type are related contravariantly (in reverse), so even though key is related to N, it's not the case that N is related to the particular key denoted by key. As an example of why it is correct to flag an error, consider this usage.
consta=foo1<'x'|'y'>('x');consty: string=a.y// not really a string.
The best that you could do is some constructive process, but this just illustrates the issue noted above:
functionfoo1<Nextendsstring>(key: N): {[keyinN]: string}{varresult:{[keyinN]: string}=<any>{};// ...// You would need to construct `result` so that it had all the keys of N, being passed by one of them.returnresult;}constx=foo1('henk');// x = { henk: string }consta=foo1<'x'|'y'>('x');// a = {x: string; y: string; }
Search Terms
object key string literal
Suggestion
I'm trying to write a function to set a field in an object using a string literal type. I can write the signature for it, but I can't write the body. A simplified version of it looks like this:
I imagine this has something to do with the keys of an object literal being declared to be
string
and the stronger typeN extends string
getting dropped on the floor?But the code feels like it is correct and it feels like the type system should be able to see that.
Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: