Search Terms
Casting, type casting, functional type casting, cast, string as number, cast utility type
This is similar to #15048, but I think the proposal is different enough to warrant a new issue (if the community disagrees, I'm happy to close the issue).
Suggestion
This might not be a practical idea, but I'd love to see the inclusion of some sort of Cast type that takes a generic argument similar to Partial. So running Cast<number> would return things that can be generally cast as numbers.
Use Cases
I came across a need for this while developing a polyfill for the ElementInternals spec. As part of that specification there are ARIA properties to interact with an element's Accessibility Object Model, so things like ariaValueMax. Run the following code in Chrome and notice the last line yields a string.
class X extends HTMLElement {
internals = this.attachInternals();
}
customElements.define('x-x', X);
let x = new X();
x.internals.ariaValueMax = 5000;
x.internals.ariaValueMax; // returns '5000'
Granted, this is bizarre behavior, but I was hoping there would be a way to accept 5000 | '5000', but not 'five thousand' as part of the type checking.
Examples
I would imagine this could be used like the following:
interface AriaValues {
ariaValueMax: Cast<number>;
ariaValueMin: Cast<number>;
ariaValueNow: Cast<number>;
ariaValueText: string;
}
Another trivial example would be a concatenate function where users might be able to concatenate different types together:
function concatenate(first: Cast<string>, last: Cast<string>): string {
return first.toString() + last.toString();
}
Checklist
My suggestion meets these guidelines:
Search Terms
Casting, type casting, functional type casting, cast, string as number, cast utility type
This is similar to #15048, but I think the proposal is different enough to warrant a new issue (if the community disagrees, I'm happy to close the issue).
Suggestion
This might not be a practical idea, but I'd love to see the inclusion of some sort of
Casttype that takes a generic argument similar toPartial. So runningCast<number>would return things that can be generally cast as numbers.Use Cases
I came across a need for this while developing a polyfill for the
ElementInternalsspec. As part of that specification there are ARIA properties to interact with an element's Accessibility Object Model, so things likeariaValueMax. Run the following code in Chrome and notice the last line yields a string.Granted, this is bizarre behavior, but I was hoping there would be a way to accept
5000 | '5000', but not'five thousand' as part of the type checking.Examples
I would imagine this could be used like the following:
Another trivial example would be a concatenate function where users might be able to concatenate different types together:
Checklist
My suggestion meets these guidelines: