我可以指定一个数组不能被赋值给记录类型吗?

4

我有一个类型为Record<number, MyType>的成员。 目前,我也可以将数组分配给它。 我明白:数组是一个对象(typeof [] => 'object'),而索引是键。 但是,我能否告诉编译器,我不想允许将数组传递给我的Record<int, WhateverType>类型变量?

const myRecord: Record<number, MyType> = []; // <= would like to have an error here

数组是由数字索引的记录,那么这个分配对你来说有什么问题? - Maciej Sikora
1
@MaciejSikora 这会让其他开发人员误以为具有连续索引的记录是可行的,而实际上结构更像是查找。 - Andrei V
什么是 int?它是一个小的 bigint 吗? - jcalz
@jcalz 哎呀!老毛病了,你懂的... 这只是我编译器错误的10%而已。 - Andrei V
1个回答

5

一个定制的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

Code sample:

代码示例


“readonly”关键字的原因是什么?我不得不将其删除,因为它不允许动态添加新条目(例如myRecordReformed2[5] = "nope";)。 - Andrei V
1
很好,那只是从“ArrayLike”类型复制的代码。在这里没有相关性,所以从答案中删除了它。 - ford04

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接