我有一个关于打字类型推断的问题.这里有一个简单的例子.

interface Student {
  readonly ids: number[],
}
const ids: readonly number[] = [1, 2, 3];
let student: Student = { ids: ids };

此代码片段显示以下错误消息:

The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.

似乎类型推断要求{ ids: ids }内的值为ids的类型必须具有number[]而不是readonly number[]的类型.

我可以把const ids: readonly number[] = [1, 2, 3];中的readonlygo 掉,或者把let student: Student = { ids: ids };改成let student: Student = { ids: ids.map(id => id) };.

推荐答案

您将属性设置为只读,而不是属性的类型.您实际上应该做的是:

interface Student {
  ids: readonly number[];
}

测试:

const ids: readonly number[] = [1, 2, 3];
let student: Student = { ids: ids }; // no error

不同之处在于,您可以防止场本身发生Mutations :

let student: Student = { ids: [] };

student.ids = [1]; // Cannot assign to 'ids' because it is a read-only property

Typescript相关问答推荐

Angular 过滤器形式基于某些条件的数组控制

是否可以根据嵌套属性来更改接口中属性的类型?

类型脚本接口索引签名

如何根据另一个属性的布尔值来缩小函数属性的返回类型?

如何设置绝对路径和相对路径的类型?

如何键入函数以只接受映射到其他一些特定类型的参数类型?

TypeScrip:基于参数的条件返回类型

material 表不渲染任何数据

部分类型化非 struct 化对象参数

在函数中打字推断记录的关键字

以Angular 执行其他组件的函数

正确使用相交类型的打字集

React router 6(数据路由)使用数据重定向

Angular material 无法显示通过API获取的数据

为什么上下文类型在`fn|curred(Fn)`的联合中不起作用?

Typescript .根据枚举输入参数返回不同的对象类型

如何使用useSearchParams保持状态

如何使用 Angular 确定给定值是否与应用程序中特定单选按钮的值匹配?

如何在由函数参数推断的记录类型中具有多个对象字段类型

Typescript 编译错误:TS2339:类型string上不存在属性props