Tengo un tipo que se parece a esto:
type Location=`${number},${number};${number},${number};...` ¿Hay algún tipo de utilidad como Repeat<T> que pueda hacer esto por mí? Me gusta esto:
type Location=Repeat<`${number},${number};`>Puede elegir directamente el tipo string si lo desea como:
type myLocation = string; const myLocation: myLocation = "123123123"; console.log(myLocation); de lo contrario, si desea reducirlo, es mejor declararlo const como:
const myLocation = "123123123"; console.log(myLocation); entonces su tipo será el valor de myLocation
No creo que haya una manera de definir un patrón repetido infinito para un tipo que usa en la declaración de variables.
Sin embargo, un tipo de protección en una función puede verificar que una cadena coincida con un patrón infinito, así (patio de recreo ):
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;"); // 👍 matches onlyAcceptsLocation("12,34;56,78"); // ⚠️ onlyAcceptsLocation("12'34;56,78;"); // ⚠️ onlyAcceptsLocation("1,2,3;45,67;"); // ⚠️Puede usar una aserción as const para obtener un tipo de literal de cadena de un literal de plantilla, como este:
const str1 = 'str1'; const str2 = `${str1},${str1};${str1},${str1}` as const; // type is "str1,str1;str1,str1"SOLO FUNCIONA EN TS >=4.5
Es posible crear un tipo independiente.
Por favor vea este ejemplo:
type Coordinates = `${number},${number};` type MAXIMUM_ALLOWED_BOUNDARY = 50 type Last<T extends string[]> = T extends [...infer _, infer Last] ? Last : never; type ConcatPrevious<T extends any[]> = Last<T> extends string ? `${Last<T>}${Coordinates}` : never type Mapped< N extends number, Result extends Array<unknown> = [Coordinates], > = (Result['length'] extends N ? Result : Mapped<N, [...Result, ConcatPrevious<Result>]> ) // type MyLocation = // | `${number},${number};` // | `${number},${number};${number},${number};` // | `${number},${number};${number},${number};${number},${number};` // | `${number},${number};${number},${number};${number},${number};${number},${number};` // | `${number},${number};${number},${number};${number},${number};${number},${number};${number},${number};` // | ... 44 more ... // | `${number},${number};${number},${number};${number},${number};${number},${number};${number},${number};${number},${number}; .... type MyLocation = Mapped<MAXIMUM_ALLOWED_BOUNDARY>[number] const myLocation1: MyLocation = '45,56;67,68;' // ok const myLocation2: MyLocation = '45,56;67,68;1,2;3,4;5,6;7,8;9,10;' // ok const myLocation3: MyLocation = '45,56;67,68;1,2;3,4;5,6;7,8;9,10,' // expected error Mapped son un tipo de utilidad que representa un ciclo while . Itera hasta que la longitud de Result alcance N . En otras palabras, Mapped<10> - iterará 10 veces. Vea este ejemplo en js puro:
const mapped = (N: number, Result: any[] = []): string => { if (N === Result.length) { return Result.join('') } const x = Math.random(); const y = Math.random() return mapped(N, [...Result, `${x},${y};`]) } Es difícil representar uniones en js, por eso he usado join('') . Espero que quede claro cómo funciona.
Si desea aumentar MAXIMUM_ALLOWED_BOUNDARY a 500, calentará su CPU, así que tenga cuidado.
Como habrás notado, es imposible representar un patrón recursivo para el tipo en el script de tipo, pero es posible crear una unión lo suficientemente grande.
Tenga en cuenta que existen algunos inconvenientes del tipo ${number} . Se le permite usar números con ceros a la izquierda como aquí:
const x: `${number}` = '01'.