[英]In Typescript, how to use a string literal type in an interface?
重复问题正在解决一个略有不同的问题。 这是特定于在interface
使用类型的。
我想在接口中使用字符串文字类型。 我敢肯定,我对这个问题的答案只有一点点变化。
下面是我的代码的一个简化示例,它显示了错误。
我需要更改什么才能让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"'.
错误信息截图:
我需要更改什么才能让
barFunction(baz)
没有以下 Typescript 错误?
您无法使用barFunction
做任何barFunction
。 问题不在这里。 事实上,你对baz
的定义被扩大了。
为了缓解它,请使用显式类型定义:
const baz: Bar = { x: 'a' }
……或者不太理想,但也是一个解决方案:
barFunction(baz as Bar)
使用 TypeScript 3.4,我们还可以做到:
const baz = { x: 'a' } as const
这将使 TypeScript 将'a'
视为字符串文字,而不仅仅是任何string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.