Rename key of typescript object type

后端 未结 1 666
温柔的废话
温柔的废话 2020-12-31 17:00

I have this:

type Two = {
  one: number,
  two: string,
  three: boolean
}

I want it to create a type that would look like this:

         


        
相关标签:
1条回答
  • 2020-12-31 17:57

    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;
    // }
    
    0 讨论(0)
提交回复
热议问题