简体   繁体   中英

Is it possible to have a numeric string type in TypeScript?

Update: I now realize that I had overlooked how strings are handled during runtime, so 100 + 5 wouldn't actually work like I had expected. I'll leave this up to see if anyone has a better solution for my issue that's not type casting or type definitions.

I've been looking all over, so I apologize if this is a duplicate question, however I was wondering if it is possible to define a TypeScript type for numerical strings that takes either a string or a value and then indicates it will always be a number? I work with sending data to a number of different systems and, unfortunately, I have no control over the model definitions (they're controlled by the various teams that own the data). This leaves me with having to cast all the strings to numbers to do calculations and then back to strings to keep the IDE happy and results in a lot of extra work.

I'd love if I could do something like the following, it would help reduce the amount of redundant work:

type NumericalString<T extends number | string> = T extends (string | number) ? number : never;

let someVal: NumericalString = "100"; // Recognized as 100 by IDE

// ... elsewhere in code
if (isNumericalString(someVal)) {
    someVal+= 5; // No need to cast to number because IDE already knows it's a number
}

I'd especially love it if there was a way for TypeScript to be smart and know that "100" was a valid numeric string, but that "Foobar" wasn't, but I'd settle for being able to trick the IDE into thinking ALL strings were numbers when assigned as NumericStrings and deal with the ramifications of that, given that I'm the only one actively working on this project.

I appreciate any help on this, I feel like I lose a good hour / hour and a half a day to this and would love to boost my productivity, if able.

Here both numbers and string as number will be accepted but any other string can not be accepted

type NumericalString = `${number}` | number;

let str: NumericalString = "120"; // OK
let num: NumericalString = 120; // OK

let someOtherStr: NumericalString = "Any Thing Than Num"; // Show error by IDE

I assume you want to overload the += operator. This isn't supported by TypeScript at the moment. You have to cast that manually, as far as I know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM