【问题标题】:In Typescript, how to use a string literal type in an interface?在 Typescript 中,如何在接口中使用字符串文字类型?
【发布时间】:2019-03-04 00:22:36
【问题描述】:

duplicate issue 正在解决一个稍微不同的问题。这是特定于在 interface 中使用类型的。


我想在界面中使用string literal type。我确信我离这个问题的答案只有一点点改变。

下面是我的代码的简化示例,它显示了错误。

我需要更改什么才能让barFunction(baz) 没有以下 Typescript 错误?

// foo.ts

type Name = 'a' | 'b'
interface Bar {
  x: Name
}

const n: Name = 'a'

const barFunction = (bar: Bar) => console.log(bar)

barFunction({ x: 'a' })

const baz = { x: 'a' }
barFunction(baz) // <-- error here

错误信息

Argument of type '{ x: string; }' is not assignable to parameter of type 'Bar'.  
  Types of property 'x' are incompatible.  
    Type 'string' is not assignable to type '"a"'.  

错误信息截图:

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我需要更改什么才能让barFunction(baz) 没有 下面是打字稿错误?

    barFunction 无能为力。问题不存在。事实上,你对baz 的定义被扩大了。

    为了减轻它,使用显式类型定义:

    const baz: Bar = { x: 'a' }
    

    …或者不太理想,但也是一种解决方案:

    barFunction(baz as Bar)
    

    使用 TypeScript 3.4,我们也可以做到:

    const baz = { x: 'a' } as const
    

    这将使 TypeScript 将 'a' 视为字符串文字,而不仅仅是任何 string

    【讨论】:

    • 谢谢。我还发现我可以使用barFunction(baz as Bar) 解决错误。在创建 const 时使用您的建议来转换类型比在函数调用中定义更有意义,以便在一个地方解决问题。
    猜你喜欢
    • 2019-08-19
    • 2023-03-21
    • 2017-05-07
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    相关资源
    最近更新 更多