TypeScript里的工具类型Partial的用法
生活随笔
收集整理的這篇文章主要介紹了
TypeScript里的工具类型Partial的用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在SAP Spartacus的源代碼里我們可以觀察到很多Partial的使用場景:
Partial 可以快速把某個接口類型中定義的屬性變成可選的(Optional):
interface People {age: number;name: string; }const Jerry:People = {age: 10,name: 'Jerry' };const Tom: People = {name: 'Tom' }上述代碼會發生編譯時錯誤:
1.ts:11:7 - error TS2741: Property ‘age’ is missing in type ‘{ name: string; }’ but required in type ‘People’.
解決方法:
interface People {age: number;name: string; }const Jerry:People = {age: 10,name: 'Jerry' };type AnonymousPeople = Partial<People>;const tom:AnonymousPeople = {name: 'Tom' };編譯之后:
var Jerry = {age: 10,name: 'Jerry' }; var tom = {name: 'Tom' };這個工具類型的實現毫無神奇之處:
type Partial<T> = {[P in keyof T]?: T[P]; };我們完全可以自行實現:
interface People {age: number;name: string; }const Jerry:People = {age: 10,name: 'Jerry' };type JerryPartial<T> = {[P in keyof T]?: T[P]; };type AnonymousPeople = JerryPartial<People>;const tom:AnonymousPeople = {name: 'Tom' };更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的TypeScript里的工具类型Partial的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何加强对项目进度的监管和控制
- 下一篇: 通过环境变量注入的方式启动SAP Spa