Skip to content

infer type fail when type is ([k1, t1] | [k2, t2])[] like #36374

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
bluelovers opened this issue Jan 23, 2020 · 1 comment
Closed

infer type fail when type is ([k1, t1] | [k2, t2])[] like #36374

bluelovers opened this issue Jan 23, 2020 · 1 comment

Comments

@bluelovers
Copy link
Contributor

TypeScript Version: Version 3.8.0-dev.20200123

Search Terms:

Code

export type IEntrie = (
	['a', string]
	| ['b', string]
	| ['c', string]
	| ['d', string]
	| ['e', number]
	)

export default (Object.entries({}) as IEntrie[])
.map(([siteID, table]) => {

	if (siteID === 'e')
	{

		console.dir(siteID) // infer should is 'e
		console.dir(table + 0) // infer should is number

		return {
			siteID,
			table,
		}
	}
	else
	{
		console.dir(siteID) // infer should is a b c d
		console.dir(table) // infer should is string

		return {
			siteID,
			table,
		}
	}
})

Expected behavior:

when siteID is e, table should is number, not string | number
when siteID is not e, table should is string, not string | number

export declare type IEntrie = (['a', string] | ['b', string] | ['c', string] | ['d', string] | ['e', number]);
declare const _default: ({
    siteID: "e";
    table: number;
} | {
    siteID: "a" | "b" | "c" | "d";
    table: string;
})[];
export default _default;

Actual behavior:

Error:(20, 15) TS2365: Operator '+' cannot be applied to types 'string | number' and 'number'.

image

export declare type IEntrie = (['a', string] | ['b', string] | ['c', string] | ['d', string] | ['e', number]);
declare const _default: ({
    siteID: "e";
    table: string | number;
} | {
    siteID: "a" | "b" | "c" | "d";
    table: string | number;
})[];
export default _default;

Playground Link:

Related Issues:

@nmain100
Copy link

Duplicate of #32639 which is a duplicate of #12184. My search terms were "dependent narrowing".

Everything works as expected if you don't destructure into [siteID, table], but once you do you have two separate variables and Typescript doesn't track the relation between narrowing one causing a narrowing of the other.

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