arrays - 我可以指定一个数组不可分配给记录吗?
问题描述
我有一个 type 的成员Record<number, MyType>
。目前,我还可以为它分配一个数组。我明白了:数组是一个对象(typeof [] => 'object'
),索引是键。但是,是否可以告诉编译器我不想允许将数组传递给我的类型变量Record<int, WhateverType>
?
const myRecord: Record<number, MyType> = []; // <= would like to have an error here
解决方案
自定义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
推荐阅读
- flutter - 如何在颤动中调用输入值?
- python - Tkinter:“元组”没有属性“键”
- typescript - React Hooks:为什么 setState 不会导致 Context.provider 重新渲染?
- c# - 天蓝色存储队列中的最大出队计数
- c# - C# UI 自动化焦点事件不适用于记事本++
- python - 测量旋转矩阵之间的差异
- sql - 通过动态 SQL 函数返回值
- excel - 在 Microsoft Excel 或 Google 表格中对相应类别的值进行排名
- java - android中的随机按钮
- python - 将无法转换为整数的值替换为零 python pandas