Issue
I have source type defined as:
unit: 'hour'|'day'|'week'|'month'
I am using it as lowercase for moment.js library. Bu I also need it uppercase for backend endpoint. So my http method accepts parameter as
unit: 'HOUR'|'DAY'|'WEEK'|'MONTH'
But the typescript does not accept conversion via toUpperCase in method call.
Argument of type 'string' is not assignable to parameter of type 'HOUR'|'DAY'|'WEEK'|'MONTH'
Is there an elegant solution in typescript that I will not destroy static type checking and in the same time I will not make extra convertor helper function (custom toUpperCase)?
Thanks for advices! :)
Solution
You can extend the declaration of toUpperCase
to have an extra overload that takes this specific union of string literal types and returns the upper case version of the union type. There is no extra function, just an extra compile time declaration:
interface String {
toUpperCase(this: 'hour'|'day'|'week'|'month') : 'HOUR'|'DAY'|'WEEK'|'MONTH'
}
declare let low: 'hour'|'day'|'week'|'month';
let up = low.toUpperCase(); // typed as "HOUR" | "DAY" | "WEEK" | "MONTH"
Note
If you are in a module you will need to redeclare string in the global namespace:
declare global {
interface String {
toUpperCase(this: 'hour' | 'day' | 'week' | 'month'): 'HOUR' | 'DAY' | 'WEEK' | 'MONTH'
}
}
Answered By - Titian Cernicova-Dragomir
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.