Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename key of typescript object type

Tags:

typescript

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.

like image 897
Eduard Avatar asked Oct 08 '18 12:10

Eduard


People also ask

How do you define a type with dynamic keys in typescript?

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.

How to rename object key in JavaScript?

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.

How to re-map keys in mapped types in typescript?

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]

How to rename multiple properties of a string?

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


1 Answers

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;
// }
like image 171
Titian Cernicova-Dragomir Avatar answered Sep 19 '22 10:09

Titian Cernicova-Dragomir