首页 > 其他分享 >Typescript类型体操 - Append to object

Typescript类型体操 - Append to object

时间:2022-09-06 21:12:36浏览次数:100  
标签:Typescript AppendToObject object Test type id Append

题目

中文

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

例如:

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;
}

在线演示

标签:Typescript,AppendToObject,object,Test,type,id,Append
From: https://www.cnblogs.com/laggage/p/16663312.html

相关文章

  • Typescript类型体操 - Flatten
    题目中文在这个挑战中,你需要写一个接受数组的类型,并且返回扁平化的数组类型。例如:typeflatten=Flatten<[1,2,[3,4],[[[5]]]]>//[1,2,3,4,5]EnglishIn......
  • Typescript类型体操 - Length of String
    题目中文计算字符串的长度,类似于String#length。EnglishComputethelengthofastringliteral,whichbehaveslikeString#length.答案解法1typeStringToArr......
  • [Typescript Challenges] 15. Medium - Omit
    Implementthebuilt-in Omit<T,K> genericwithoutusingit.Constructsatypebypickingallpropertiesfrom T andthenremoving KForexampleinterfaceT......
  • Python源码解析-dict的底层实现(PyDictObject)
    目录简介PyDictObject对象类型创建dict缓存池本文基于Python3.10.4。简介元素与元素之间通常可能会存在某种联系,这个联系将两个元素关联在一起。为了刻画这种关联关系,编......
  • Typescript类型体操 - Append Argument
    题目中文实现一个泛型AppendArgument<Fn,A>,对于给定的函数类型Fn,以及一个任意类型A,返回一个新的函数G。G拥有Fn的所有参数并在末尾追加类型为A的参数。typeF......
  • Typescript类型体操 - Parameters
    题目中文实现内置的Parameters<T>类型,而不是直接使用它,可参考TypeScript官方文档。例如:constfoo=(arg1:string,arg2:number):void=>{}typeFunctionParams......
  • Typescript类型体操 - ReplaceAll
    答案中文实现ReplaceAll<S,From,To>将一个字符串S中的所有子字符串From替换为To。例如typereplaced=ReplaceAll<'types','',''>//期望是'types'......
  • Typescript类型体操 - Replace
    题目中文实现Replace<S,From,To>将字符串S中的第一个子字符串From替换为To。例如typereplaced=Replace<'typesarefun!','fun','awesome'>//期望是......
  • Python源码解析-list对象的底层实现(PyListObject)
    目录简介PyListObject内存管理创建list缓存池管理本文基于Python3.10.4。简介数组是程序中一个十分重要的概念,我们将符合某一特性的多个元素集合在一块形成一个数组,同时......
  • js判断变量数据类型typeof、instanceof、Object.prototype.toString.call()、 constru
    JavaScript有4种方法判断变量的类型,分别是typeof、instanceof、Object.prototype.toString.call()(对象原型链判断方法)、constructor(用于引用数据类型) typeof:常用于......