Typescript-为什么无法推断此字符串文字类型? [英] Typescript - Why can't this string literal type be inferred?

查看:158
本文介绍了Typescript-为什么无法推断此字符串文字类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段未通过类型检查:

The following snippet does not pass the type check:

type TaskType = 'SIMPLE' | 'COMPLEX'

interface TaskDefinition {
    name: string,
    task: string,
    taskType: TaskType
};

const test: TaskDefinition = { 
    name: '',
    task: '',
    taskType: 'SIMPLE' // This is fine
};

const tasks : TaskDefinition[] = ["apples", "pears"].map(i => {
    return {
        name: i,
        task: i,
        taskType: 'SIMPLE' // This one is not
    };
})

{名称:字符串;任务:字符串; taskType:字符串; } [] 不可分配 键入 TaskDefinition [].

{ name: string; task: string; taskType: string; }[] is not assignable to type TaskDefinition[].

尽管目标类型为TaskDefinition

这是什么原因导致的,我该如何解决?

What's causing this and how can I fix it?

推荐答案

Typescript仅在将其分配给const时才会推断字符串文字类型.当创建对象文字时,编译器将为字符串常量而非字符串文字类型推断string.如果直接将对象文字分配给需要字符串文字类型的对象,那是可以的,因为在这种情况下,编译器仅检查字符串常量是否可分配给字符串文字类型.

Typescript will infer string literal types only when you assign it to a const. When you are creating object literals, the compiler will infer string for string constants not string literal types. If you assign the object literal directly to something that requires a string literal type, that is ok, as in this case the compiler just checks that the string constant is assignable to the string literal type.

这里的简单解决方案是为map指定类型参数,这仍将保留对map的返回值的编译器检查:

The simple solution here is to specify the type argument to map, this will still preserve compiler checks on the return value from map :

const tasks = ["apples", "pears"].map<TaskDefinition>(i => {
    return {
        name: i,
        task: i,
        taskType: 'SIMPLE'
    };
})

或在字符串上使用类型断言为预期的字符串文字类型:

Or to use a type assertion on the string to the expected string literal type:

const tasks:TaskDefinition[] = ["apples", "pears"].map(i => {
    return {
        name: i,
        task: i,
        taskType: 'SIMPLE' as 'SIMPLE'
    };
}) 

修改 由于打字稿3.4( PR ),您还可以使用as const断言来获取字符串文字类型:

Edit Since typescript 3.4 (PR) you can also use an as const assertion to get the string literal type:

const tasks:TaskDefinition[] = ["apples", "pears"].map(i => {
    return {
        name: i,
        task: i,
        taskType: 'SIMPLE' as const
    };
}) 

结束编辑

您也可以直接在返回值上键入assert,但这将禁用对返回值的某些检查:

You could also type assert directly on the return value, but this will disable some checks on the return value:

const tasks:TaskDefinition[] = ["apples", "pears"].map(i => {
    return <TaskDefinition>{
        wrongValue: "", // no error since we are asserting
        name: i,
        task: i,
        taskType: 'SIMPLE'
    };
}) 

这篇关于Typescript-为什么无法推断此字符串文字类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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