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
.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-10-18 11:00:00 +0000
Seen: 7 times
Last updated: Feb 25 '22
How can one ensure that sub-classes have uniform method parameters in TypeScript?
Can a TypeScript definition for icon names be provided in MaterialCommunityIcons for React Native?
How can TypeScript be used to save a file in an Excel add-in?
What is the Angular Type script NG Zorro event for radio buttons?
What is the process for implementing a Many to Many relationship using NestJs Sequlize and Mysql2?
What is the method for defining a Fixed length Array in TypeScript?
What difficulties are encountered in the installation of react-router-dom using typescript?