Support relations and inference between template literal types by ahejlsberg · Pull Request #43361 · microsoft/TypeScript (original) (raw)

With this PR we support relations and inference between template literal types. Specifically, when the target side in a type relation is a template literal type, the source side is now permitted to be a compatible (i.e. more specific) template literal type. Likewise, when inferring to a template literal target type, we now permit the source type to also be a template literal type.

Some examples of improved assignment relations:

declare let s1: ${number}-${number}-${number}; declare let s2: 1-2-3; declare let s3: ${number}-2-3; declare let s4: 1-${number}-3; declare let s5: 1-2-${number}; declare let s6: ${number}-2-${number}; s1 = s2; s1 = s3; s1 = s4; s1 = s5; s1 = s6;

With this PR all of the above assignments are permitted, where previously only the first assignment was permitted.

Some examples of inference between template literal types:

declare function foo1(arg: *${V}*): V;

function test(s: string, n: number, b: boolean, t: T) { let x1 = foo('hello'); // "hello" let x2 = foo('hello'); // "hello" let x3 = foo(*${s}* as const); // string let x4 = foo(*${n}* as const); // ${number} let x5 = foo(*${b}* as const); // "true" | "false" let x6 = foo(*${t}* as const); // ${T} let x7 = foo(**${s}** as const); // *${string}* }

Fixes #43060.
Fixes #43243.