Skip to content

infer type of tuple from single elements #15484

@phra

Description

@phra

hi,

while working on await-to-ts i discovered that i cannot publish the to function with the return type of Promise<[Error, null] | [null, T]> but only with Promise<[Error, T]> because it cannot infer correctly the tuple type on partial informations on elements. you can find a live example of this in this branch
schermata da 2017-05-01 00-35-42

TypeScript Version: 2.3.1

Code
playground link

function f(flag: boolean): [number] | [string] {
	if (flag) {
		return [0]
	}

	return ['0']
}

const res = f(true)[0]
if (typeof res === 'number') {
	res // is a number, it works correctly
} else {
	res // is a string, it works correctly
}

const res2 = f(true)
if (typeof res2[0] === 'number') {
	const tmp1 = res[0] // is string | number, it should be number
} else {
	res // is a string, it works correctly
}


function g(flag: boolean): [number, string] | [string, number] {
	if (flag) {
		return [0, '0']
	}

	return ['0', 0]
}

const res1 = g(true)
if (typeof res1[0] === 'number') {
	const tmp1 = res1[0] // is string | number, it should be number
	const tmp2 = res1[1] // is string | number, it should be string
} else {
	const tmp1 = res1[0] // is string | number, it shuold be string
	const tmp2 = res1[1] // is string | number, it should be number
}

Expected behavior:
based on partial informations, the type system should be able to infer tuple type correctly.
Actual behavior:
the type system fails to infer tuple types with partial informations about elements.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions