Created
January 20, 2023 08:52
-
-
Save TheodorRene/49ec1dfe9cd5aa0fe7f61cb80eed2c3f to your computer and use it in GitHub Desktop.
Change the type of the given keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type ChangeTypeOfKey<T, K extends keyof T, H> = { | |
[Key in keyof T]: Key extends K ? H : T[Key]; | |
}; | |
type K = {id:string, name:string, date:string} | |
type KL = ChangeTypeOfKey<K, 'id', string | null> | |
// ^? {id:string|null, name:string} | |
type E = {id:string, name:string, date:string} | |
type EL = ChangeTypeOfKey<K, 'id'|'name', boolean> | |
// ^? {id:boolean, name:boolean, date:string} |
Could also be done with a combination of Omit
and &
. Basically removing a key and then adding it with a different type.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBDAnmYcDCALAhgOwObAAqywA8gGYDSwiAPIQDRyVygzA4AmAznANY0I5OIzgAJAHxwAvHADeAKDhwA2tURwAljn6DhhALoAuZjVYh2XXiwD84uCcJqaBgNwKAvu+UKkKZjLympxG3DBQ2nhMOFgAtsCh4ZFMnFjsiRH4Hr4kzAAygZi4BMQoFOq0lEwA5MHVTGGZeHAAPnA4AK4ANl1SCgD0-XAAenZywRmRLZ090XEJjZHZPso+fqgAooHjIYv4c-GT+3Cp6Xt42etwGwWyRfhEJOU0lTV1LdUx8fVwAEYQEC6wFwfUGIzsQRC-0BwJwBwS0KBuBSaQWSSyQA