3 ms·
Template string types are neat, and I'm excited to see what new functionality is afforded. I've already been able to use them for probably ill-advised magic (.
by dllthomas 6y ago
Template string types are neat, and I'm excited to see what new functionality is afforded. I've already been able to use them for probably ill-advised magic (... not in production anywhere), like this type for "strings with no leading or trailing spaces":
type RSTRIP<STR> = STR extends `${infer T} ` ? RSTRIP<T> : STR;
type LSTRIP<STR> = STR extends ` ${infer T}` ? LSTRIP<T> : STR;
type STRIP<STR> = RSTRIP<LSTRIP<STR>>;
which allows things like:
function strip<T extends string>(str: T): STRIP<T> {
return str.trim() as STRIP<T>;
}
function printStripped<T>(str: STRIP<T>) {
console.log(str);
}
printStripped('hi');
//X printStripped(' hi');
printStripped(strip(' hi'));