Regrettably, TypeScript lacks a specific type for strings consisting only of characters from a particular set. The ongoing proposal suggests incorporating regular expression validated string types; refer to the current open issue on microsoft/TypeScript#41160. If such types were available, you could potentially write something like
// NOT VALID TS, avoid doing this:
type DNAStrand = /[GCTA]*/;
This, however, is not feasible at the moment. To increase the chances of implementation in the future, consider expressing your interest and use case on the relevant issue.
Although TypeScript offers template literal types for some character-wise manipulations of string literal types, representing complex structures like DNAStrand
as unions or recursive types faces limitations:
// NOT VALID TS, avoid doing this:
type DNAStrand = "" | `${DNA}${DNAStrand}`
Due to circular dependencies, the compiler would struggle with such representations. Instead, a workaround using a recursive conditional type can be implemented for shorter lengths:
type RepeatLessThan<N extends number, T extends string, A extends string[] = [""]> =
N extends A['length'] ? A[number] : RepeatLessThan<N, T, [`${T}${A[0]}`, ...A]>
// example for short lengths
type DNAStandUpToThree = RepeatLessThan<4, DNA>;
However, TypeScript's limitations restrict the representation of large unions, making it challenging to cater to extremely long strings like DNA strands.
An alternate approach involves utilizing template literals to create a generic type that validates input strings against a certain format, providing runtime verification instead of compile-time safety:
type VerifyDNAStrand<T extends string, A extends string = ""> =
T extends `${infer F}${infer R}` ?
F extends DNA ? VerifyDNAStrand<R, `${A}${F}`> : `${A}${DNA}` :
A
To handle type validation during runtime, a helper function using generics can ensure data integrity:
const dnaStrand = <T extends string>(
x: T extends VerifyDNAStrand<T> ? T : VerifyDNAStrand<T>) => x;
... (remaining content shortened for brevity) ...