用最简单的话讲解Utility Types-Required

背景

上次学习输出,记录了Partial干嘛用的(把字段必选变成可选),源码如何实现。产出后就感觉特别的空虚,感觉还是要慢慢完善这个水系列文章。所以如何把握有限的摸鱼时间,输出水文,那就是再挑个简单的Utility Types来讲解讲解,所以今天的主角是Required(把字段可选变成必选)

正文

官方例子

先来看下官方的例子,以及说明

Constructs a type consisting of all properties of Type set to required. The opposite of Partial.

interface Props {
  a?: number;
  b?: string;
}
 
const obj: Props = { a: 5 };
 
const obj2: Required<Props> = { a: 5 }; // Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.
复制代码

这个官方的例子,简直太简单易懂了,所以遇事不决真相就是看文档。你看这一开始声明的接口Props,两个可选字段ab,你看这报错提示,提示的信息多么完整,虽然你的Props的a和b字段都是可选,但在我Required包裹下,你们一个都逃不了!b属性缺失,因为你用了Required(水文章的快乐就是一个一个字陪着读者再一起念一遍)

源码讲解

直接上源码

/**
 * Make all properties in T required
 */
type Required<T> = {
    [P in keyof T]-?: T[P];
};
复制代码

源码时间讲解开始,和上次的其实差不多,还是一样的keyof T取类型中的字段,还是一样的P in进行遍历,又有一样的T[P]获取每个字段的类型,唯一不一样的是看到个-?,不过猜测一下,就是把可选属性删掉变成必选,哈哈XDM你们猜的没错,这种骚操作是在TS2.8版本加入的豪华套餐(点击此处看链接),不高兴点链接的这边把对应的example贴出来,xdm可以看下

/**
 * TypeScript 2.8 adds the ability for a mapped type to either add or remove a particular modifier. Specifically, a readonly or ? property modifier in a mapped type can now be prefixed with either + or - to indicate that the modifier should be added or removed.
 */ 
type MutableRequired<T> = { -readonly [P in keyof T]-?: T[P] }; // Remove readonly and ?
type ReadonlyPartial<T> = { +readonly [P in keyof T]+?: T[P] }; // Add readonly and ?
复制代码

所以这篇水文到此结束,完结撒花!

参考

猜你喜欢

转载自juejin.im/post/7018822641414832135