Typescript 编译器将为 const 推断字符串文字类型:
const a = 'abc';
const b: 'abc' = a; // okay, a is of type 'abc' rather than string
Run Code Online (Sandbox Code Playgroud)
但是,对于属性,类型被推断为string。
const x = {
y: 'def',
};
const z: { y: 'def' } = x; // error because x.y is of type string
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我怎样才能让编译器在不为 编写类型注释的情况下推断出它x的类型?{ y: 'def' }x
编辑:有一个未决问题请求支持此功能。一种建议的解决方法是使用如下语法:
const x = new class {
readonly y: 'def';
};
const z: { readonly y: 'def' } = x; // Works
Run Code Online (Sandbox Code Playgroud)
在此处的Playground 中尝试。
编辑 2:甚至有一个公开的PR可以解决这个问题。禁用类型扩展似乎是一个流行的要求。
我认为您正在寻找TS 3.4 中添加的const 断言。
您只需添加as const到字符串即可使其成为文字类型。
const x = {
y: 'def' as const,
};
const z: { y: 'def' } = x; // no error :)
Run Code Online (Sandbox Code Playgroud)
不同之处在于没有const属性关键字。由于无法确保属性不会发生变化,因此 TS 无法假设常量字符串文字,因此它必须假设更通用的string.
const尝试在该位置将示例中的第一个替换为let和 ,TS 也会假设stringand not 'abc':
let a = 'abc';
const b: 'abc' = a;
Run Code Online (Sandbox Code Playgroud)
将显示b“字符串类型无法分配给类型‘abc’”的错误。
由于 TS 无法从语言功能推断出不变性,就像您在const变量示例中所做的那样,唯一的方法是通过显式类型注释告诉它 objct 属性是不可变的,这意味着您的问题的答案是否定的。