Back to Type Challenges

README.Zh CN

questions/02759-medium-requiredbykeys/README.zh-CN.md

latest1.7 KB
Original Source
<!--info-header-start--><h1>RequiredByKeys </h1><blockquote><p>by jiangshan <a href="https://github.com/jiangshanmeta" target="_blank">@jiangshanmeta</a></p></blockquote><p><a href="https://tsch.js.org/2759/play/zh-CN" target="_blank"></a> &nbsp;&nbsp;&nbsp;<a href="./README.md" target="_blank"></a> </p><!--info-header-end-->

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

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

例如:

ts
interface User {
  name?: string
  age?: number
  address?: string
}

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

<!--info-footer-start-->

<a href="../../README.zh-CN.md" target="_blank"></a> <a href="https://tsch.js.org/2759/answer/zh-CN" target="_blank"></a> <a href="https://tsch.js.org/2759/solutions" target="_blank"></a> <!--info-footer-end-->