And*_*i V 4 arrays record typescript
我有一个类型为 的成员Record<number, MyType>。目前,我还可以为其分配一个数组。我明白了:数组是一个对象(typeof [] => 'object'),索引是键。但是,是否可以告诉编译器我不想允许将数组传递给我的类型变量Record<int, WhateverType>?
const myRecord: Record<number, MyType> = []; // <= would like to have an error here
Run Code Online (Sandbox Code Playgroud)
自定义NumberRecord类型可以通过强制不存在属性来排除数组length(类似于ArrayLike内置声明):
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
Run Code Online (Sandbox Code Playgroud)