type TUnion = "foo"|"bar"|"qux"
function fn(value:TUnion) {
switch(value){
case "bar": return '';
case "foo": return true;
case "qux": return 1;
default: throw Error('invalid value')
}
}
let a = fn("bar")
let a: string | number | boolean
type TUnion = "foo"|"bar"|"qux"
function fn(value: "foo"): boolean;
function fn(value: "bar"): string;
function fn(value: "qux"): number;
function fn(value: TUnion): string | boolean | number {
switch(value){
case "bar": return '';
case "foo": return true;
case "qux": return 1;
default: throw Error('invalid value')
}
}
let f = fn("foo"); // f: boolean
let b = fn("bar"); // b: string
let q = fn("qux"); // q: number
type TResult = {
foo: boolean;
bar: string;
qux: number;
}
type TUnion = keyof TResult;
function fn<T extends TUnion>(value: T): TResult[T] {
switch (value) {
case 'bar': return '' as TResult[T];
case 'foo': return true as TResult[T];
case 'qux': return 1 as TResult[T];
default: throw new Error('Invalid value');
}
}
let a = fn('bar');