在Typescript中,如何在接口中使用字符串文字类型?

时间:2019-03-04 00:22:36

标签: typescript

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"'.  

错误消息的屏幕截图:

Error Message

1 个答案:

答案 0 :(得分:1)

  

要使barFunction(baz)不具有   低于Typescript错误?

barFunction无能为力。问题不在那里。事实上,您对baz的定义已经扩大。

为了缓解这种情况,请使用显式类型定义:

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

…或不太理想,但也可以解决:

barFunction(baz as Bar)

使用TypeScript 3.4,我们还可以:

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

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