首页 > 其他分享 >Typescript类型体操 - PartialRequired

Typescript类型体操 - PartialRequired

时间:2022-09-21 20:01:03浏览次数:84  
标签:Typescript string RequiredByKeys number PartialRequired 体操 address type name

题目

中文

实现一个通用的RequiredByKeys<T, K>,它接收两个类型参数TK

K指定应设为必选的T的属性集。当没有提供K时,它就和普通的Required<T>一样使所有的属性成为必选的。

例如:

interface User {
    name?: string;
    age?: number;
    address?: string;
}
type UserRequiredName = RequiredByKeys<User, 'name'>; // { name: string; age?: number; address?: string }

English

Implement a generic RequiredByKeys<T, K> which takes two type argument T and K.

K specify the set of properties of T that should set to be required. When K is not provided, it should make all properties required just like the normal Required<T>.

For example

interface User {
    name?: string;
    age?: number;
    address?: string;
}
type UserRequiredName = RequiredByKeys<User, 'name'>; // { name: string; age?: number; address?: string }

答案

type RequiredByKeys<
    T extends object,
    K extends keyof T | string = keyof T,
    H = {
        [P in K extends keyof T ? K : never]: Exclude<T[P], null | undefined>;
    } & { [P in Exclude<keyof T, K>]?: T[P] }
> = { [P in keyof H]: H[P] };

在线演示

标签:Typescript,string,RequiredByKeys,number,PartialRequired,体操,address,type,name
From: https://www.cnblogs.com/laggage/p/type-challenge-required-by-keys.html

相关文章

  • TypeScript(一)基本使用
    一:导入TypeScriptnpmitypescript或者npmitypescript-g(全局导入) 二:编译Ts文件为Js(道理跟Sass转Css一样)在当前文件目录终端中输入:tsc文件名称.ts然后就......
  • 03:TypeScript — 从初学者到专家 |对象、数组和函数
    03:TypeScript—从初学者到专家|对象、数组和函数级别:初学者我们已经了解了什么是变量以及如何使用语句设置它们。我们还看到了可用于指定值类型的不同原始类型。当我......
  • Typescript类型体操 - EndsWith
    题目中文实现EndsWith<T,U>,接收两个string类型参数,然后判断T是否以U结尾,根据结果返回true或false例如:typea=EndsWith<'abc','bc'>;//expectedtobefals......
  • Typescript类型体操 - StartsWith
    题目中文实现StartsWith<T,U>,接收两个string类型参数,然后判断T是否以U开头,根据结果返回true或false例如:typea=StartsWith<'abc','ac'>;//expectedtobe......
  • Typescript类型体操 - RemoveIndexSignature
    题目中文实现RemoveIndexSignature<T>,将索引字段从对象中排除掉.示例:typeFoo={[key:string]:any;foo():void;};typeA=RemoveIndexSignature<......
  • Typescript类型体操 - PickByType
    题目中文找出T中类型为U的属性示例:typeOnlyBoolean=PickByType<{name:string;count:number;isReadonly:boolean;isE......
  • Typescript类型体操 - MinusOne
    题目中文给定一个正整数作为类型的参数,要求返回的类型是该数字减1。例如:typeZero=MinusOne<1>;//0typeFiftyFour=MinusOne<55>;//54EnglishGivenanu......
  • typescript-变量
    1.变量赋值了类型就不能赋值其他类型1leta:number;2letb:string;3a=10;45//不可以6//a="assdf";7b="123"2.如果变量的声明和赋值是同时......
  • Typescript类型体操 - PercentageParser
    题目中文实现类型PercentageParser。根据规则/^(\+|\-)?(\d*)?(\%)?$/匹配类型T。匹配的结果由三部分组成,分别是:[正负号,数字,单位],如果没有匹配,则默认是空字符串......
  • Typescript类型体操 - DropChar
    题目中文从字符串中剔除指定字符。例如:typeButterfly=DropChar<'butterfly!',''>;//'butterfly!'EnglishDropaspecifiedcharfromastring.......