TypeScript readonly 数组属性赋值错误

Jer*_*uan 3 type-inference typescript

我有一个关于 TypeScript 类型推断的问题。这是一个简单的例子。

interface Student {
  readonly ids: number[],
}
const ids: readonly number[] = [1, 2, 3];
let student: Student = { ids: ids };
Run Code Online (Sandbox Code Playgroud)

此代码片段抱怨以下错误消息:

The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.
Run Code Online (Sandbox Code Playgroud)

看来类型推断要求ids里面的值的类型{ ids: ids }必须是 的类型number[]而不是 的类型readonly number[]

我可以删除readonlyinconst ids: readonly number[] = [1, 2, 3];或更改let student: Student = { ids: ids };let student: Student = { ids: ids.map(id => id) };.

won*_*ame 5

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

interface Student {
  ids: readonly number[];
}
Run Code Online (Sandbox Code Playgroud)

测试:

const ids: readonly number[] = [1, 2, 3];
let student: Student = { ids: ids }; // no error
Run Code Online (Sandbox Code Playgroud)

不同之处在于您正在防止字段本身发生变化:

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

student.ids = [1]; // Cannot assign to 'ids' because it is a read-only property
Run Code Online (Sandbox Code Playgroud)