Typescript: Type ‘string’ is not assignable to type ‘”numeric” | “2-digit”‘ in Date::toLocaleDateString()

When you initialize a class property with a literal such as public foo = { bar: 'a' }, its type becomes { bar: string }, even if you declare it as readonly. TypeScript on purpose doesn’t make the type too strict ({ bar: 'a' }).

Method toLocaleDateString accepts an object whose key year must be of type 'numeric' or '2-digit', but yours is of type string.

To make the type of the initialized object more specific, use as const:

public static dateOptions = { year: 'numeric', month: '2-digit', day: '2-digit' } as const;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)