Typescript 类型“string”不可分配给类型““|”、“|”、“|”
在我的班上,我有一个属性:Typescript 类型“string”不可分配给类型““|”、“|”、“|”,typescript,Typescript,在我的班上,我有一个属性: thousandSeparator: '' | ',' | ' ' | '.'; 并希望将其设置为: const options = { thousandSeparator: ',' }; 设置此选项时,我会得到错误 Types of property 'thousandSeparator' are incompatible. Type 'string' is not assignable to type '"" | ",&q
thousandSeparator: '' | ',' | ' ' | '.';
并希望将其设置为:
const options = {
thousandSeparator: ','
};
设置此选项时,我会得到错误
Types of property 'thousandSeparator' are incompatible.
Type 'string' is not assignable to type '"" | "," | " " | "."'.
您的代码在应用程序中运行良好 如果代码中有更多内容,例如在将字符串设置为变量之前在别处定义字符串,则必须强制转换它,如下所示:
type thousandSeparator = '' | ',' | ' ' | '.';
const options = {
thousandSeparator: ',' as thousandSeparator,
};
如果要将options.thousandSeparator分配给类型|','|''''.'.'TLDR:use const options={thousandSeparator:','as const};所以“,”实际上是类型“,”而不是扩展到类型“string”。