Skip to content

Create a Cast utility type #41120

@calebdwilliams

Description

@calebdwilliams

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:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions