[英]How to declare Typescript type that is AnyRecord OR an object array?
In short, I want to do this:简而言之,我想这样做:
interface Rec {
key: string;
}
type RecordOrList = Record<string, any> | Rec[];
So, RecordOrList
is either some object, or a list of specific objects.因此,
RecordOrList
要么是一些 object,要么是特定对象的列表。
However, typescript here seems to treat arrays of Rec
-s as Any Records.但是,这里的 typescript 似乎将
Rec
-s 的 arrays 视为任何记录。 For example, this is valid code, but I was expecting it to be a type error ("int instead of string").例如,这是有效的代码,但我希望它是一个类型错误(“int 而不是 string”)。
const x: RecordOrList = [{
key: 123,
}];
https://www.typescriptlang.org/play?ts=4.5.4#code/JYOwLgpgTgZghgYwgAgEoQcg3gWAFDLIDWEAngFzIDOYUoA5gNz4C+++YpADiuggPZQAJgHkoAGWA1kAXjQZBQgDw06IegBpkcEKQB8yAD7yEAbQC6zPPgEhpAD0p9FYydLmncBYmUoBGACYAZg1WSyA https://www.typescriptlang.org/play?ts=4.5.4#code/JYOwLgpgTgZghgYwgAgEoQcg3gWAFDLIDWEAngFzIDOYUoA5gNz4C+++YpADiuggPZQAJgHkoAGWA1kAXjQZBQgDw06IegBpkcEKQB8yAD7yEAbQC6zPPgEhpAD0p9FYydLmncBYmUoBGACYAZg1WSyA
How can I make the code above type checked?如何检查上述类型的代码?
The issue you're having here is that arrays themselves are - surprisingly - a valid Record<string, any>
(specifically, it's a Record<"length", number>
).您在这里遇到的问题是 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"]
Instead of any
, you could use unknown
here:您可以在此处使用
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",
}];
Or just narrow your Record value type to a list of scalar types.或者只是将您的记录值类型缩小为标量类型列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.