-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Cannot safely, generically add a property to a record #38796
Comments
On further thought, this wouldn't actually be safe, because
I guess this is a feature request then, to have some way of accepting a single property name as a parameter so this can be safe. I don't have a specific design offhand. |
MotivationI want to create a hierachical builder that accepts property names as strings and builds an object with those properties. For (a simplified) example: |
I can't tell what you're trying to do here - please boil this down to something more actionable if you'd like us to follow up more. Thanks! |
General feature requestHave a type-safe way to accept a string parameter and use it as a property name. In other words, a way to write the following code without the cast: function add<TObject, TName extends string, TValue>(
obj: TObject, name: TName, value: TValue) {
return {...obj, [name]: value} as TObject & {[name in TName]: TValue};
} This may require some way of accepting a single property name as a parameter (as opposed to |
Got it - this would be a duplicate (or at least dependent on) of #27808 then |
TypeScript Version: v4.0.0-dev.20200525, 3.9.2
Search Terms: object intersection record
Code
Expected behavior:
No compiler errors
Actual behavior:
Playground Link
Additional attempts:
I couldn't find any way to make this work without a cast; no matter what I tried, the property
[name]: value
is inferred as[x: string]: TValue
, ignoringTName
. Other attempt:Playground Link
Related Issues: Possibly #18538
The text was updated successfully, but these errors were encountered: