【发布时间】:2017-12-02 08:56:33
【问题描述】:
Typescript 编译器将为 consts 推断字符串文字类型:
const a = 'abc';
const b: 'abc' = a; // okay, a is of type 'abc' rather than string
但是,对于属性,类型被推断为string。
const x = {
y: 'def',
};
const z: { y: 'def' } = x; // error because x.y is of type string
在此示例中,如何让编译器推断 x 的类型为 { y: 'def' } 而无需为 x 编写类型注释?
编辑:有一个开放的issue 请求支持此功能。一种建议的解决方法是使用如下语法:
const x = new class {
readonly y: 'def';
};
const z: { readonly y: 'def' } = x; // Works
在 Playground 中尝试here。
编辑 2: 甚至还有一个开放的PR 可以解决这个问题。禁用类型扩展似乎是一个流行的请求。
【问题讨论】:
-
你可以用type assertion告诉编译器某些东西有特定的类型:
const x = { y: 'def' as 'def', };
标签: typescript