Typescript类型体操 - Append to object

题目

中文

实现一个为接口添加一个新字段的类型。该类型接收三个参数,返回带有新字段的接口类型。

例如:

type Test = { id: '1' }
type Result = AppendToObject<Test, 'value', 4> // expected to be { id: '1', value: 4 }

English

Implement a type that adds a new field to the interface. The type takes the three arguments. The output should be an object with the new field.

For example

type Test = { id: '1' }
type Result = AppendToObject<Test, 'value', 4> // expected to be { id: '1', value: 4 }

答案

type AppendToObject<T extends object, U extends string, V> = {
  [P in (keyof T) | U]: P extends keyof T ? T[P] : V;
}

在线演示

posted @ 2022-09-06 21:02  Laggage  阅读(56)  评论(0编辑  收藏  举报