Skip to content

Cannot use conditional type to strongly type this type hint for callback #55533

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
mqudsi opened this issue Aug 27, 2023 · 2 comments
Closed

Comments

@mqudsi
Copy link

mqudsi commented Aug 27, 2023

πŸ”Ž Search Terms

"conditional this type"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about conditional types, infer,

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.2.2#code/GYVwdgxgLglg9mABAWwIYAcA8AVANAVVwGFEBeRcAEwFNgYxrKA+ACigAsYBnALkQEEAToNQBPHE1yIIqADayARqggBrPm069EJagA8o1MJS4Ujteo0QB+AcLETEfAHIInIeagWzqmIpMQAbnIg1Hx4iPQ0unxgIMgK1IJSqHaiYQDaALoAlGRMiISIHNxCAOZWfETZfPhZiADeAFCILdIIXFCIgtRc7lA1deRZANzNrRDtnRNgBvpkRZpl1jbFXKOtiMBwgogs3p0w8wAMwxGImAvcAHTeYKUcpwDUjzC5TRsb0x1F86vpMJl1h8Wl9OiB5jJ5EpVFdIbIWNNZlApMiIijNNkgcDur1ZFB-pl5iAsYgAL5jFrdKAgQRIHF9Uak0ZAA

πŸ’» Code

function map<T,U,C = undefined>(this: Array<T>, callback: (this: C extends undefined ? Array<T> : NonNullable<C>, value: T, index: number, array: T[]) => U, thisArg?: C): U[] {
    const result: U[] = [];
    const context = thisArg ?? this;
    for (let i = 0; i < this.length; ++i) {
        const t = this[i];
        const u = callback.call(context, t, i, this);
        result[i] = u;
    }
    return result;
};

πŸ™ Actual behavior

TypeScript seems to be unable to resolve the conditional assignment to context with the conditional type C extends undefined ? Array<T> : NonNullable<C>

πŸ™‚ Expected behavior

tsc should be able to deduce that the type of context matches the type of callback's this type hint.

Additional information about the issue

I tried a number of different variations for the conditional assignment of context, trying to see if the problem was with when I was this to context, but all of the ones I tried gave me variations of the same error.

  • this ?? thisArg
  • typeof thisArg === "undefined" ? this : thisArg
  • typeof thisArg === "undefined" ? this : <NonNullable<C>> thisArg

(Obviously using <any> in any number of places in the code would work around the issue.)

@fatcerberus
Copy link

Similar to #33912; conditional types aren't related to the results of control-flow analysis so you'll have to cast.

@mqudsi
Copy link
Author

mqudsi commented Aug 27, 2023

Thanks.

Closing as a duplicate of #33912

@mqudsi mqudsi closed this as not planned Won't fix, can't repro, duplicate, stale Aug 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants