Hary
Hary

Reputation: 5818

string' is not assignable to type 'string'

I am trying to write a NumericHelper.ts where it returns the regex with configurable fraction digits.

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

And this is returning the error below unless it is casted back to any. But why? This function is returning string.

Type '(fractionDigits?: number) => string' is not assignable to type 'string'.ts(2322)

Upvotes: 0

Views: 131

Answers (2)

epascarello
epascarello

Reputation: 207501

You have the types set in the wrong place

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

Personally I think it is cleaner without the fat arrow

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

Upvotes: 1

mwilson
mwilson

Reputation: 12900

GET_DECIMAL_PATTERN isn't of the type string, it's a function that returns a string:

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

Upvotes: 1

Related Questions