I have a type that looks something like this:
type Location=`${number},${number};${number},${number};...`
Is there a Utility type like Repeat<T> that can do this for me?
like this:
type Location=Repeat<`${number},${number};`>
CodePudding user response:
You can directly choose type string if you want as:
type myLocation = string;
const myLocation: myLocation = "123123123";
console.log(myLocation);
else if you want to narrow it down then better to declare it const as:
const myLocation = "123123123";
console.log(myLocation);
then your type will be the value of the myLocation
CodePudding user response:
I don't think there is a way to define an infinite repeating pattern for a type that you use on variable declaration.
However, a type guard on a function can check that a string matches an infinite pattern, like so (playground):
type MatchesPattern<Pattern extends string, Current extends string> = Current extends `` ? string : (Current extends `${Pattern}${infer Rest}` ? MatchesPattern<Pattern, Rest> : never);
type LocationPattern = `${number},${number};`;
declare function onlyAcceptsLocation<L extends string & IsLocation, IsLocation = MatchesPattern<LocationPattern, L>>(location: L): void;
onlyAcceptsLocation("12,34;56,78;"); // 
