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"'.
错误消息的屏幕截图:
答案 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
。