首页 > 其他分享 >[Typescript] 93. Hard - Get Required

[Typescript] 93. Hard - Get Required

时间:2022-11-10 22:13:59浏览次数:36  
标签:Typescript _____________ Get type Required Key 93 foo GetRequired

Implement the advanced util type GetRequired<T>, which remains all the required fields

For example

type I = GetRequired<{ foo: number, bar?: string }> // expected to be { foo: number }

 

First thing need to understand how to know whether a prop is requried or not?

Idea: T[Key] extends Required<T>[Key] ? true: false

type GetRequired<T extends Record<PropertyKey, any>> = {
  [Key in keyof T]: T[Key] extends Required<T>[Key] ? true: false
}
type x = GetRequired<{ foo: number; bar?: string }>
/*
type x = {
    foo: true;
    bar?: false | undefined;
}
*/

 

With this Tip in mind, what we need to do is just check whether Key is required or not, if it is required, then keep it, if it is not requried, then set never.

/* _____________ Your Code Here _____________ */

type GetRequired<T extends Record<PropertyKey, any>> = {
  [Key in keyof T as T[Key] extends Required<T>[Key] ? Key: never]: T[Key]
}

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

type cases = [
  Expect<Equal<GetRequired<{ foo: number; bar?: string }>, { foo: number }>>,
  Expect<Equal<GetRequired<{ foo: undefined; bar?: undefined }>, { foo: undefined }>>,
]

 

标签:Typescript,_____________,Get,type,Required,Key,93,foo,GetRequired
From: https://www.cnblogs.com/Answer1215/p/16878946.html

相关文章

  • [Typescript] 94. Hard - Get Optional
    Implementtheadvancedutiltype GetOptional<T>,whichremainsalltheoptionalfieldsForexampletypeI=GetOptional<{foo:number,bar?:string}>//expe......
  • TypeScript(基础篇)day01
    一.TS介绍1.1简介ts是2012年由微软开发,在js的基础上添加了类型支持1.2优劣势优势:任何位置都有代码提示,增加效率;类型系统重构更容易;使用最新的ECMAscript语法劣势:和......
  • 记录--Uniapp + TypeScript 配置文档
    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助0目标使用uniapp +TypeScript为基础栈进行小程序开发uniapp是一个使用Vue.js开发所有前端......
  • typescript 学习笔记
    前言:学习一门新的知识,首要的问题就是概念,这里记录下一.[any,unkonw]的区别any不做类型判断,可以任意[赋值,使用]1let_a:any="1";//ok2_a=1;//ok3co......
  • 【python】点燃我,温暖你 ,快来Get同款~
    前言大家早好、午好、晚好吖❤~最近,一部名叫《点燃我,温暖你》得电视剧冲进了大家得视野~讲述得是肆意张扬的编程天才李峋与勇敢坚韧的少女学霸朱韵从青涩校园到职场......
  • Leetcode第864题:获取所有钥匙的最短路径(Shortest path to get all keys)
    解题思路想到最短路径问题,自然想到用BFS解决问题,但是只记录位置还不够,还需要记录当前拥有的钥匙状态。需要的数据结构钥匙的个数是\(1-6\),用一个二进制数表示钥匙的状......
  • 前段使用get获取文件流,实现下载
    functiondownLoad(){    constiframe=document.createElement('iframe')    iframe.style.display='none'    iframe.style.height=......
  • simpread-TypeScript 小状况之遍历对象属性 - 掘金
    本文由简悦SimpRead转码,原文地址juejin.cn在TypeScript里面,当需要遍历对象的时候,经常就会遇到下图所示的错误提示。前言最近开始在复杂项目中使用TypeScri......
  • C# get、set 说明
    一、get、set的基本简介  在面向对象编程(OOP)中,是不允许外界直接对类的成员变量直接访问的,既然不能访问,那定义这些成员变量还有什么意义呢?所以C#中就要用set和get方法来......
  • simpread-typescript 注释大法
    本文由简悦SimpRead转码,原文地址zhuanlan.zhihu.com函数、interface、enum、type、var的申明建议使用文档注释(持续更新中)apifunction/***获取店铺签约......