Home > OS >  "string extends S" in Typescript template string conditional
"string extends S" in Typescript template string conditional

Time:11-03

In the original PR to implement template strings, Hejlsberg gives an example for a split type function:

type Split<S extends string, D extends string> =
    string extends S ? string[] :
    S extends '' ? [] :
    S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] :
    [S];

What is the purpose of the constraint string extends S? Is that simply to allow for type T = Split<string> ?

CodePudding user response:

Yes, that is its purpose. Without the check, all the conditionals would evaluate to the false-branch which would give the result [string] if string was given for S.

This is fine as far as the conditional type is concerned as it was not able to split the string. But in TypeScript, we often try to model the runtime behaviour of JavaScript. And given an unknown string, we simply don't know if it can or can not be split into multiple strings at runtime. That's why we need to add this conservative check to return string[] instead.

  • Related