-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
CFA doesn't work when using generics to associate two function arguments #50205
Comments
The error is correct. You wrongly assume that navigateTo<'/user' | '/product'>('/user', { productId: '..' }); You want #27808. |
Actually, |
It's allowed to explicitly specify the type parameter, as I did. In that case the type parameter is not inferred anymore. But even if you let it infer the type you can have the same issue: const path = '/user' as '/user' | '/product'
navigateTo(path, { productId: '..' }); Within the implementation of the function the compiler can't know if the type represents only one key, or multiple. So it errs on the safe side. |
For example, this works well: interface RouteParams {
'/user': { userId: string },
'/product': { productId: string },
'/list': { pageSize: number, current: number },
}
let key!: keyof RouteParams;
if (key === '/user') {
//@ts-expect-error
if (key === '/product') {
}
} So why it doesn't works inside the function ? function navigateTo<T extends keyof RouteParams>(url: T, params: RouteParams[T]) {
if (url === '/user') {
//@ts-expect-error
if (url === '/product') {
}
}
} |
No. You're only narrowing the type of the specific variable.
|
Actually // 【THIS WORKS !】
function test(v: 'a' | 'b') {
if (v === 'a') {
//@ts-expect-error
if (v === 'b') {
}
}
}
// 【WHY THIS DOESN'T WORKS ?】
function test2<T extends 'a' | 'b'>(v: T) {
if (v === 'a') {
//@ts-expect-error
if (v === 'b') {
}
}
} |
Union types strike again! This recent comment of mine #50145 (comment) comes to mind, specifically the last part:
|
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
🔎 Search Terms
CFA generic function
🕗 Version & Regression Information
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
CFA works well outside the function call, but not works inside the function.
🙂 Expected behavior
Compile successfully.
The text was updated successfully, but these errors were encountered: