Ask Your Question
3

What is the process for selecting specific keys and giving them new names in Typescript?

asked 2021-10-18 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-02-25 10:00:00 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-10-18 11:00:00 +0000

Seen: 7 times

Last updated: Feb 25 '22