如何提示 Typescript 编译器推断属性的字符串文字类型? [英] How can I hint to the Typescript compiler to infer string literal types for properties?

查看:30
本文介绍了如何提示 Typescript 编译器推断属性的字符串文字类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Typescript 编译器将为 const 推断字符串文字类型:

The Typescript compiler will infer a string literal type for consts:

const a = 'abc';
const b: 'abc' = a; // okay, a is of type 'abc' rather than string

但是,对于属性,类型被推断为 string.

However, for properties, the type is inferred to be string.

const x = {
    y: 'def',
};

const z: { y: 'def' } = x; // error because x.y is of type string

在此示例中,如何让编译器推断 x 的类型为 { y: 'def' } 而不为 编写类型注释x?

In this example, how can I get the compiler to infer that x is of type { y: 'def' } without writing a type annotation for x?

有一个开放的问题请求支持此功能.一种建议的解决方法是使用如下语法:

There's an open issue requesting support for this feature. One suggested workaround is to use syntax like this:

const x = new class {
    readonly y: 'def';
};

const z: { readonly y: 'def' } = x; // Works

在 Playground 中试用 此处.

Try it in Playground here.

编辑 2: 甚至还有一个开放的 PR会解决这个问题.禁用类型扩展似乎是一个受欢迎的请求.

Edit 2: There's even an open PR that would solve this problem. Disabling type widening seems to be a popular request.

推荐答案

不同之处在于属性没有 const 关键字.由于无法确保属性不会发生变异 TS 不能假设常量字符串文字,因此它必须假设更通用的 string.

The difference is there is no const keyword for properties. Since there is no way to be sure the properties won't be mutated TS cannot assume a constant string literal, it has to assume the more generic string.

尝试用 let 替换示例中的第一个 const,并且在该位置 TS 也将假定 string 而不是 'abc':

Try replacing the first const in your example with let and at that location too TS is going to assume string and not 'abc':

let a = 'abc';
const b: 'abc' = a; 

此代码的 TS Playground 链接

将显示 b 的错误类型字符串不可分配给类型 'abc'".

Is going to show an error for b "Type string is not assignable to type 'abc'".

由于 TS 无法从语言特性推断不变性,正如您在 const 变量示例中所做的那样,唯一的方法是通过显式类型注释告诉它 obejct 属性是不可变的,这意味着你的问题的答案是否定的.

Since TS cannot infer immutability from a language feature, as you do in your const variables example, the only way is to tell it that the obejct property is immutable is via an explicit type annotation, meaning the answer to your question is a negative.

这篇关于如何提示 Typescript 编译器推断属性的字符串文字类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆