Using a generic typed class, I would like some methods to be available ONLY IF generic type is 'string'.
With the following code
class MyClass<T = string> {
value: T = null;
setDate(m: Moment) {
// could be used only if T is string
value = m ? m.format('YYYY-MM-DD') : null;
}
}
gives me the error
Argument of type 'string' is not assignable to parameter of type 'T'
which is really clear and totally intended : Moment.format() returns a string. :D
Is there a proper way to make the setDate() method avaible only if T is string ?
By advance, thank you very much.
I know I can fix the problem using m.format('YYYY-MM-DD') as unknown as T but it looks like a workaround, not a real typescript solution.
And I know about Conditional Types but I don't think it could fix my problem. At least, I did not find how to figure it out.