![](/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.