Repository navigation
Open
Labels
Domain: check: Type InferenceRelated to type inference performed during signature resolution or `infer` type resolutionPossible ImprovementThe current behavior isn't wrong, but it's possible to see that it might be better in some cases
Milestone
Description
π 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
π» 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
Reacted by Nodar Chkuaselidze
Metadata
Metadata
Assignees
Labels
Domain: check: Type InferenceRelated to type inference performed during signature resolution or `infer` type resolutionPossible ImprovementThe current behavior isn't wrong, but it's possible to see that it might be better in some cases
Activity
Andarist commentedon May 3, 2024
In a sense, this could be seen as a duplicate of #13948 . Like I mentioned here the computed properties like this are always widened - without considering the contextual property keys.
A somewhat related thing to this is that those assignments work because index signatures turn off common property checking:
This is OK but it would - IMHO - make sense for this to participate in the common property check. You can see a different issue related to this: #55709
Xriuk commentedon May 17, 2024
Not sure if it's related to this but I'm facing a similar problem:
Here
Matchisneverbecause apparently it matches/AnyStringas/${number}and then fails becauseAnyStringis not anumber.