test
处存在 TypeScript 错误。type Test = {
obj: object;
arr: string[];
};
export const test: Test = {
obj: {},
arr: ['foo'],
} as const;
错误提示:
Type '{ readonly obj: {}; readonly arr: readonly ["foo"]; }' is not assignable to type 'Test'. Types of property 'arr' are incompatible. The type 'readonly ["foo"]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.
我想在 test
中使用 as const
(导致错误),因为 test
不应该被更改。与此同时,我将拥有其他可变的类型为 Test
的变量,因此我不能让任何一个字段是 readonly
。如何使错误消失并实现我的目标?
令人困惑的是,obj
没有引起错误。数组在技术上是对象。
as const
断言的显式类型。您应该选择使用其中之一。 - captain-yossarian from Ukraineas const
将arr
的类型缩小为一个元组(固定大小的数组),其元素为字符串字面量类型 - 在这种情况下是['foo']
。由于['foo']
比string[]
更具体,因此不被允许。这样理解正确吗? - GregL