类型'string'不可分配给类型'“” | “,” | “” | “。”'

时间:2020-08-13 09:06:56

标签: typescript

在我的课堂上,我有一个财产:

thousandSeparator: '' | ',' | ' ' | '.';

,并希望通过以下方式进行设置:

const options = {
  thousandSeparator: ','
};

设置此项时出现错误

 Types of property 'thousandSeparator' are incompatible.
 Type 'string' is not assignable to type '"" | "," | " " | "."'.

1 个答案:

答案 0 :(得分:1)

您的代码在tsc playground

中工作正常

如果代码中包含更多内容,例如在将字符串设置为变量之前在其他地方定义字符串,则必须进行强制转换,如下所示:

type thousandSeparator = '' | ',' | ' ' | '.';

const options = {
  thousandSeparator: ',' as thousandSeparator,
};