【问题标题】:Type 'string' is not assignable to type '"" | "," | " " | "."' [duplicate]类型 'string' 不可分配给类型 '"" | "," | " " | “。“' [复制]
【发布时间】:2023-03-24 14:05:01
【问题描述】:

在我的班级我有一个财产:

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

并希望通过以下方式设置它:

const options = {
  thousandSeparator: ','
};

设置时出现错误

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

【问题讨论】:

  • options.thousandSeparator 应该是 const 如果你想将它分配给类型'' | ',' | ' ' | '.'
  • TLDR:使用const options = { thousandSeparator: ',' as const }; 所以',' 实际上是',' 类型,并且没有扩大到'string' 类型。

标签: typescript


【解决方案1】:

您的代码在tsc playground 中运行良好

如果您的代码有更多内容,例如在将字符串设置为变量之前在别处定义字符串,则必须将其强制转换,如下所示:

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

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

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 2021-04-28
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    相关资源
    最近更新 更多