I have this:
type Two = {
one: number,
two: string,
three: boolean
}
I want it to create a type that would look like this:
type RenamedTwo = {
one: number,
two: string,
four: boolean // difference
}
Tried to create it this way:
type Rename<T, K extends keyof T, N> = Pick<T, Exclude<keyof T, K>> & { [N]: T[K] }
In an attempt to use this way:
type Renamed = Rename<Two, 'three', 'four'>
But TSlint marks [N]
as error and gives this error message:
[ts] A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type. [ts] 'N' only refers to a type, but is being used as a value here.
Define a Type for Object with Dynamic keys in TypeScript# Use an index signature to define a type for an object with dynamic keys, e.g. [key: string]: string;. Index signatures are used when we don't know all of the names of a type's properties ahead of time, but know the shape of the values.
Rename object key in JavaScript. JavaScript doesn’t provide an inbuilt function to rename an object key. So we will look at different approaches to accomplish this in this article. In JavaScript, objects are used to store collection of various data. It is a collection of properties.
In TypeScript 4.1 and onwards, you can re-map keys in mapped types with an as clause in a mapped type: type MappedTypeWithNewProperties<Type> = { [Properties in keyof Type as NewKeyType]: Type[Properties]
In case someone wants to rename multiple properties, here is the type definition: type Rename<T, K extends keyof T, N extends string> = Pick<T, Exclude<keyof T, K>> & Record<N, valueof<Pick<T, K>>> – Eduard Oct 9 '18 at 8:06 Add a comment | 1 Answer 1 ActiveOldestVotes 14
You need to use a mapped type for the renamed property as well:
type Two = {
one: number,
two: string,
three: boolean
}
type Rename<T, K extends keyof T, N extends string> = Pick<T, Exclude<keyof T, K>> & { [P in N]: T[K] }
type Renamed = Rename<Two, 'three', 'four'>
Note that this will not work as expected if you provide more properties:
type Renamed = Rename<Two, 'two' |'three' , 'four' | 'five'> // will be Pick<Two, "one"> & {
// four: string | boolean;
// five: string | boolean;
// }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With