You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
typeTheProps={first: {arg0: string;arg1: string;}second: {arg0: number;arg2: boolean;}third: {arg3: string;arg4: number;}}declareconsttryCb: <KextendskeyofTheProps>(propName: K,cb: (props: TheProps[K])=>void)=>voidtryCb('second',props=>console.log(props.arg2))// => no error (although this should also be an error)consttryFunc=<KextendskeyofTheProps>(propName: K,props: TheProps[K])=>{if(propName=='second'){console.log(props.arg2)// => error here}}
🙁 Actual behavior
Property does not exist on selected type, but available via callback
🙂 Expected behavior
no error occurs same as using callback
Additional information about the issue
No response
The text was updated successfully, but these errors were encountered:
This is not a bug in TS. The caller chooses the type argument (which is why you can do this when you call your function). The implementation needs to handle any choice the caller makes, including things like unions:
tryFunc(Math.random()<0.999 ? 'second' : 'first',{arg0: "abc",arg1: "def"});// no compiler error
Here there is a 99.9% chance you'll see "second" as the first argument, but the second argument has no arg2 property.
I think you need #27808 if you want to be able to narrow type parameters this way. The feature at #56941 for #33014 doesn't address this because TheProps[K] is in an input position.
With tryCb the compiler infers "second" for the type argument based on the provided parameters. This is not possible within tryFuc, because within the function you can't know what type is being passed in. That's what jcalz means with "the caller chooses the type argument".
🔎 Search Terms
I was thinking this code works like how the
addEventLister
oron
behavior happens. Are there other less complex solutions?🕗 Version & Regression Information
⏯ Playground Link
https://www.typescriptlang.org/play/?#code/C4TwDgpgBAKgFhACgJwPZgM5QLxQN4BQUxUAZgJbIbABc+RJjAhsgOYAMd1y5AdqwG4GjYi1YBGLsB78hjAL7CoGCAGNUvACZ1CIkmM5ReAVwC2AIwjI5eqGIBMdc6lQAbCE143iixsDiU2vS2dmwAzFIygkrMbAAsdCYWVt5QiooEmmquLNDqvNRQ0iAAwuZ0ADwA0lAQAB7AEFpYANYQIKiksAgo6BgAfAAUYGhgAHJMphB0VQA0UKrlUMOjGHTwSKsA2lUAugCUOP1QAG6o5JqH2MdnFwQExWWDAOQq+ZrP8yN9RwsaGG4IAA6VyoVgrPpAhz7fb3fKFYoAMWMvFUOCg1VqDSamla7U63U2fSG33Gk2mUDmUFJa0JvUwOwOv10JHIXQhZKmOFwrzUGg+hxZenhgJBYI5GChbHssIUBEUQA
💻 Code
🙁 Actual behavior
Property does not exist on selected type, but available via callback
🙂 Expected behavior
no error occurs same as using callback
Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: