π Search Terms
"template literals and type inference", "type inference with dynamic template literals"
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about it
β― Playground Link
https://www.typescriptlang.org/play/?ts=5.4.5#code/C4TwDgpgBAgmCWUC8UDeAoKUDaBrCIAXFAAYAWEANpQPYB0AJKgM7ABO8AdgOYC+JAXWIAKACYBDYOOKooncQFsIxVhx5ReASmQA+KADca8Uel7p0lCMCgBXZhDYBJUSvZduyKAHJRIeQvgAYyhVdy9zAHoIqABRAA9FMEsARmIAERoIZk4vawB3GjZcOihQSCgAM0LSCBIoQPEc6wAjaC4KhzYIE0CaTlZSrOBU2ARPDCxscipaRlQ7B2d+IShoJD0JrHq+5hpLOlpuYQg6fwhNTA0AGlNI6PjEywAmYgB1QtxmdF7+62Ahl6jRAoTZTCjUeisSRBAD6oR4gmIaw2lywP12+0Ox1OinOl14NzM6CisQSCiSEAAzG8Pl90dY+p4ADwAaVWcX+nFEzCg+BANAqQJ0wkufOILJuWHEgWA8D6IgkUmIcHg2BZAm06wMRlEN01KKwJN2SighyCt3QfWE0whcwWTlE-Cuq10aEu6L2JyxJzOFy0QA
π» Code
type Api = {
[key: `hello.${string}`]: (data: { name: string }) => void
}
let userId: string = 'dynamic string'
// Example1: Doesn't work. type for `e` can't be inferred
const test1: Api = {
[`hello.${userId}`]: e => {
console.log(e.name)
},
}
// Example2: Works
const test2: Api = {
[`hello.static_string`]: e => {
console.log(e.name)
},
}
// Example3: Works
const on = <K extends keyof Api>(
key: K,
action: (data: Api[K]) => void,
) => {
// some logic
}
on(`hello.${userId}`, e => {
console.log(e.name)
})
π Actual behavior
Example 1 doesn't work, while Example 2 and Example 3 works properly. The type for e can't be inferred
π Expected behavior
To infer type of e in the Example 1.
Additional information about the issue
No response
π Search Terms
"template literals and type inference", "type inference with dynamic template literals"
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play/?ts=5.4.5#code/C4TwDgpgBAgmCWUC8UDeAoKUDaBrCIAXFAAYAWEANpQPYB0AJKgM7ABO8AdgOYC+JAXWIAKACYBDYOOKooncQFsIxVhx5ReASmQA+KADca8Uel7p0lCMCgBXZhDYBJUSvZduyKAHJRIeQvgAYyhVdy9zAHoIqABRAA9FMEsARmIAERoIZk4vawB3GjZcOihQSCgAM0LSCBIoQPEc6wAjaC4KhzYIE0CaTlZSrOBU2ARPDCxscipaRlQ7B2d+IShoJD0JrHq+5hpLOlpuYQg6fwhNTA0AGlNI6PjEywAmYgB1QtxmdF7+62Ahl6jRAoTZTCjUeisSRBAD6oR4gmIaw2lywP12+0Ox1OinOl14NzM6CisQSCiSEAAzG8Pl90dY+p4ADwAaVWcX+nFEzCg+BANAqQJ0wkufOILJuWHEgWA8D6IgkUmIcHg2BZAm06wMRlEN01KKwJN2SighyCt3QfWE0whcwWTlE-Cuq10aEu6L2JyxJzOFy0QA
π» Code
π Actual behavior
Example 1doesn't work, whileExample 2andExample 3works properly. The type forecan't be inferredπ Expected behavior
To infer type of
ein theExample 1.Additional information about the issue
No response