【问题标题】:string' is not assignable to type 'string'string' 不可分配给类型 'string'
【发布时间】:2020-05-15 00:43:50
【问题描述】:

我正在尝试编写一个NumericHelper.ts,它返回带有可配置小数位数的正则表达式。

export class NumericHelper
{
    public static  GET_DECIMAL_PATTERN: string = (fractionDigits: number = 2) => `^([0-9]*(?:[\.|,| ][0-9]{0,${fractionDigits}})?)?$`;
}

这将返回下面的错误,除非它被转换回any。但为什么?此函数正在返回字符串。

类型 '(fractionDigits?: number) => string' 不可分配给 输入“字符串”.ts(2322)

【问题讨论】:

  • 以字符串结尾,当返回特定错误时通常返回此错误,当前我无法获取错误在哪里,但要克服它,只需在 (ftact... :number = 2) : string => 最后可能添加 ...?)?$` 作为字符串;对此感到抱歉,但我困了,无法集中注意力,对此感到抱歉,希望对您有所帮助。
  • 如果也转换为字符串也会出现同样的错误
  • 我对我的评论做了一个小的更新..
  • 还是不行抱歉
  • 直接放入 public static string get_.... = ...

标签: angular typescript


【解决方案1】:

GET_DECIMAL_PATTERN 不是string 类型,它是一个返回字符串的函数:

export class NumericHelper
{
    public static GET_DECIMAL_PATTERN: Function = (fractionDigits: number = 2) => `^([0-9]*(?:[\.|,| ][0-9]{0,${fractionDigits}})?)?$`;
}

【讨论】:

    【解决方案2】:

    你的类型设置在错误的地方

    class NumericHelper
    {
        public static GET_DECIMAL_PATTERN: Function = // function here
          (fractionDigits: number = 2): string => // string here
            `^([0-9]*(?:[\.|,| ][0-9]{0,${fractionDigits}})?)?$`;
    }
    

    我个人认为没有粗箭头会更干净

    class NumericHelper {
        public static GET_DECIMAL_PATTERN (fractionDigits: number = 2): string {
            return `^([0-9]*(?:[\.|,| ][0-9]{0,${fractionDigits}})?)?$`
        }   
    }
    

    Seeing it in action with the JavaScript output

    【讨论】:

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