首页 > 其他分享 >[Typescript] 118. Hard - IsRequiredKey

[Typescript] 118. Hard - IsRequiredKey

时间:2022-11-26 16:34:19浏览次数:45  
标签:Typescript false true extends IsRequiredKey Key type 118

Implement a generic IsRequiredKey<T, K> that return whether K are required keys of T .

For example

type A = IsRequiredKey<{ a: number, b?: string },'a'> // true
type B = IsRequiredKey<{ a: number, b?: string },'b'> // false
type C = IsRequiredKey<{ a: number, b?: string },'b' | 'a'> // false

 

/* _____________ Your Code Here _____________ */
type Equal<T, U> = (<P>(x: P) => T extends P ? 1 : 2) extends (<P>(x: P) => U extends P ? 1 : 2) ? true: false;
type RequiredKeys<T> = keyof {
  [Key in keyof T as T[Key] extends Required<T>[Key] ? Key: never]: T[Key]
}
type IsRequiredKey<T, K extends keyof T> = Equal<K,RequiredKeys<T>> extends true ? true : false;

/* _____________ Test Cases _____________ */
import type { Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<IsRequiredKey<{ a: number; b?: string }, 'a'>, true>>,
  Expect<Equal<IsRequiredKey<{ a: number; b?: string }, 'b'>, false>>,
  Expect<Equal<IsRequiredKey<{ a: number; b?: string }, 'b' | 'a'>, false>>,
]

 

标签:Typescript,false,true,extends,IsRequiredKey,Key,type,118
From: https://www.cnblogs.com/Answer1215/p/16927666.html

相关文章

  • [Typescript] 117. Hard - ClassPublicKeys
    Implementthegeneric ClassPublicKeys<T> whichreturnsallpublickeysofaclass.Forexample:classA{publicstr:stringprotectednum:numberpri......
  • TypeScript学习笔记-04 tsconfig.json配置文件
    tsconfig.json一般常用的配置如下所示,可以按需要进行配置。{/*tsconfig.json是ts编译器的配置文件,ts编译器可以根据他的信息来对代码进行编译//in......
  • TypeScript编译选项
    编译选项自动编译文件编译文件时,使用-w指令后,TS编译器会自动监视文件的变化,并在文件发生变化时对文件进行重新编译。但是一次只能编译一个文件。示例:  tsc......
  • TypeScript学习笔记-03 TS基础语法
    即使有错还是可以编译为JS文件。ts方法指定参数的类型,指定返回值的类型:这样都会对返回值的类型和参数都会进行校验!......
  • TypeScript学习笔记-01TS是什么?
      TypeScript简称TS,是微软公司设计的一门语言。以JavaScript为基础构建的语言,扩展了JS、兼容JS(甚至可以在TS文件中兼容使用JS)、并且添加了类型,并且可以在任何支持JavaSc......
  • TypeScript--高级用法
    TypeScript--高级用法1.运算符可选链运算符?.判断左侧的表达式是否是null或者undefined,如果是,则会停止表达式的运行,减少我们大量的&&运算obj?.propobj?.[i......
  • TypeScript - -类型实战
    TypeScript--类型实战下面介绍的几个常见实战操作,数量不多,但是提供了一些思路,学习理解这些思路,和js实现的区别。为自己写代码的时候打下小小的基础1.实现返回promi......
  • TypeScript--5常见问题
    TypeScript--5常见问题interface和type的区别是什么||interface|type||---|---|---||可定义类型|object,array,function,classconstructor|所......
  • [Typescript] 115. Hard - Drop String
    Dropthespecifiedcharsfromastring.Forexample:typeButterfly=DropString<'foobar!','fb'>//'ooar!' /*_____________YourCodeHere_____________......
  • TypeScript类型(二)
    对象 示例://#regionjs写法//object表示一个js对象leta:object;a={};a=function(){};//#endregion//#regionTypeScript写法//{}用来指定对......