![](/img/trans.png)
[英]How to declare a specific type of empty array inside a object using typescript?
[英]How to declare Typescript type that is AnyRecord OR an object array?
簡而言之,我想這樣做:
interface Rec {
key: string;
}
type RecordOrList = Record<string, any> | Rec[];
因此, RecordOrList
要么是一些 object,要么是特定對象的列表。
但是,這里的 typescript 似乎將Rec
-s 的 arrays 視為任何記錄。 例如,這是有效的代碼,但我希望它是一個類型錯誤(“int 而不是 string”)。
const x: RecordOrList = [{
key: 123,
}];
如何檢查上述類型的代碼?
您在這里遇到的問題是 arrays本身- 令人驚訝的是 - 一個有效的Record<string, any>
(具體來說,它是一個Record<"length", number>
)。
// Valid. WTF?
const x : Record<string, any> = [];
const a : keyof [] = "length"; // Valid
const b : keyof [] = "bogus"; // Invalid
Object.getOwnPropertyNames(x); // => ["length"]
您可以在此處使用unknown
而不是any
:
interface Rec {
key: string;
}
type RecordOrList = Record<string, unknown> | Rec[];
// Type error as expected
const x: RecordOrList = [{
key: 123,
}];
// Works just fine
const y: RecordOrList = {key: 123}
const z: RecordOrList = [{
key: "123",
}];
或者只是將您的記錄值類型縮小為標量類型列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.