To select specific keys and give them new names in Typescript, you can use the interface feature of Typescript to create a new type with the required keys and their new names. Here's an example:
interface OriginalName {
key1: string;
key2: number;
key3: boolean;
}
type NewName = {
newKey1: OriginalName['key1'];
newKey2: OriginalName['key2'];
}
const obj: NewName = {
newKey1: 'value1',
newKey2: 123,
}
console.log(obj.newKey1); // 'value1'
console.log(obj.newKey2); // 123
In this example, we have an interface OriginalName
with three keys. We then create a new type NewName
that renames two of the keys to newKey1
and newKey2
.
To assign values to the keys, we use the renamed keys (newKey1
and newKey2
) in the object obj
.
When we log the values of the renamed keys in the console, they are correctly displayed as 'value1'
and 123
.
Asked: 2021-10-18 11:00:00 +0000
Seen: 7 times
Last updated: Feb 25 '22