【发布时间】:2021-05-08 23:11:37
【问题描述】:
鉴于我有这个数组:
const rooms: Rooms = [
{name: 'bathroom', neighboring: []},
{name: 'kitchen', neighboring: ['living room']},
{name: 'living room', neighboring: ['kitchen']},
] as const;
我想为Rooms 编写一个类型,它只允许neighboring 数组中的值也是name 属性的值。
我试过这样:
type Rooms = Array<{
name: string,
neighboring: RoomName[]
}>
type RoomName = typeof rooms[number]['name'];
不幸的是,这会导致 TypeScript 错误:
类型'readonly [{ readonly name: "bathroom";只读邻居:只读[]; }, ...]' 是 'readonly' 并且不能分配给可变类型 'Rooms'。
你有更好的主意吗?
【问题讨论】:
-
您报告的错误与您在问题中提出的问题无关。从
room的定义中删除as const,错误消失。如果您需要将其声明为as const,则必须将Rooms及其定义中涉及的所有类型设为只读。
标签: typescript