![](/img/trans.png)
[英]How to define mapped type for method return types in typescript 4.5.4?
[英]How to define mapped type in flow as defined in typescript
映射類型
https://www.typescriptlang.org/docs/handbook/advanced-types.html
一個常見的任務是獲取現有類型並使其每個屬性都是可選的:
interface PersonPartial {
name?: string;
age?: number;
}
或者我們可能想要一個只讀版本:
interface PersonReadonly {
readonly name: string;
readonly age: number;
}
這在Javascript中經常發生,TypeScript提供了一種基於舊類型創建新類型的方法 - 映射類型。 在映射類型中,新類型以相同的方式轉換舊類型中的每個屬性。 例如,您可以將類型的所有屬性設置為只讀或可選。 以下是幾個例子:
type Readonly<T> = {
readonly [P in keyof T]: T[P];
}
type Partial<T> = {
[P in keyof T]?: T[P];
}
並使用它:
type PersonPartial = Partial<Person>;
type ReadonlyPerson = Readonly<Person>;
如何在流程中定義這種類型?
對於readonly,有$ReadOnly
實用程序類型 。 值得注意的是,這對嵌套對象不起作用。 它也不會改變那些每個都是可選的面部,這是有道理的,因為你設置它一次並說你不能改變它。
interface PersonPartial {
name?: string;
age?: number;
}
type ReadOnly = $ReadOnly<PersonPartial>
為了使事物可選而不是只讀,你可以將readonly傳播到一個新類型:
interface PersonReadOnly {
+name: string,
+age: number
}
type PartialPerson = { ...PersonReadOnly }
這是所有這一切的嘗試流程 。
你總是可以讓自己的類型實現這些。 因此,如果您想要一個Partial
類型,您可以:
type Partial<O: {}> = { ...O }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.