![](/img/trans.png)
[英]How to force read-only arrays to have a tuple type with string literals in Typescript?
[英]Recursively setting a TypeScript type not read-only without clobbering tuples
export type DraftObject<T> = {-readonly [P in keyof T]: Draft<T[P]>}
export interface DraftArray<T> extends Array<Draft<T>> {}
export type Draft<T> = T extends any[]
? DraftArray<T[number]>
: T extends ReadonlyArray<any>
? DraftArray<T[number]>
: T extends object ? DraftObject<T> : T
type tup = [number, number, number, number]
const T: Draft<tup> = [1, 2, 3, 4]
const U: tup = [1, 2, 3, 4]
const TT: tup = T
const UU: Draft<tup> = U
DraftObject類型應返回其所有屬性都標記為非只讀的任何類型。 這在所有情況下都有效,除了元組類型(元組類型錯誤地將它們錯誤地變成數組)。 我該如何特殊化元組和Readonly<>
而不是使它們成為DraftArray
呢?
如果由於某種原因需要檢測元組和數組之間的差異,則可以使用以下事實:元組類型具有已知的"0"
鍵(字符串值,而不是數字0
),而數組則沒有:
type IfTuple<T extends any[], Y=true, N=false> = "0" extends keyof T ? Y : N
type TestTuple = IfTuple<[string, number], "tuple", "array">; // "tuple"
type TestArray = IfTuple<string[], "tuple", "array">; // "array"
這足以建立一個條件類型,該條件類型對元組所做的操作與對常規數組所做的操作有所不同。
希望能有所幫助。 祝好運!
正如jcalz所說,TypeScript 3.1尚無只讀元組。 如果您想使一切變得可變,則可以使用:
export type Draft<T> = {-readonly [P in keyof T]: Draft<T[P]>};
利用TypeScript 3.1中添加的映射元組和數組以及應用於原語的同態映射類型的先前存在的特殊情況(當T
為原語時, Draft<T>
評估為T
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.