我有一个类型为Record<number, MyType>
的成员。 目前,我也可以将数组分配给它。 我明白:数组是一个对象(typeof [] => 'object'
),而索引是键。 但是,我能否告诉编译器,我不想允许将数组传递给我的Record<int, WhateverType>
类型变量?
const myRecord: Record<number, MyType> = []; // <= would like to have an error here
我有一个类型为Record<number, MyType>
的成员。 目前,我也可以将数组分配给它。 我明白:数组是一个对象(typeof [] => 'object'
),而索引是键。 但是,我能否告诉编译器,我不想允许将数组传递给我的Record<int, WhateverType>
类型变量?
const myRecord: Record<number, MyType> = []; // <= would like to have an error here
一个定制的NumberRecord
类型可以通过强制排除数组(类似于内置声明ArrayLike
中不存在length
属性)来实现:
const t = {
0: "foo",
1: "bar"
}
const tArr = ["foo", "bar"]
type NumberRecord<T> = {
length?: undefined; // make sure, no length property (array) exists
[n: number]: T;
}
const myRecordReformed1: NumberRecord<string> = tArr; // error
const myRecordReformed2: NumberRecord<string> = t // works
myRecordReformed2[5] = "nope";
)。 - Andrei V
int
?它是一个小的bigint
吗? - jcalz