Back to Type Challenges

README

questions/02759-medium-requiredbykeys/README.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" target="_blank"></a> &nbsp;&nbsp;&nbsp;<a href="./README.zh-CN.md" target="_blank"></a> </p><!--info-header-end-->

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

typescript
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.md" target="_blank"></a> <a href="https://tsch.js.org/2759/answer" target="_blank"></a> <a href="https://tsch.js.org/2759/solutions" target="_blank"></a> <!--info-footer-end-->