-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Statically guarantee presence of object key via string literal type #33410
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
Comments
Keys in mapped type are related contravariantly (in reverse), so even though const a = foo1<'x' | 'y'>('x');
const y: 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: function foo1<N extends string>(key: N): {[key in N]: string} {
var result:{
[key in N]: string
} = <any>{};
// ...
// You would need to construct `result` so that it had all the keys of N, being passed by one of them.
return result;
}
const x = foo1('henk'); // x = { henk: string }
const a = foo1<'x' | 'y'>('x'); // a = {x: string; y: string; } |
That's a fair point. I don't suppose there is a way to restrict N to not be a union? |
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
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: