首页 > 解决方案 > 我可以指定一个数组不可分配给记录吗?

问题描述

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

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

标签: arraystypescriptrecord

解决方案


自定义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

代码示例


推荐阅读