0
比如我得到这个FN:如何根据参数字符串定义返回类型?流动型的JavaScript
const aCar = {type: 'car', wheels: 4};
const aBike = {type: 'bike', wheels: 2};
const fn = (type:'a'|'b'):Car|Bike => {
if(type === `a`) return aCar;
if(type === `b`) return aBike;
}
的问题是,回总是Bike
或Car
indipendently的类型。我想强制执行的是,当类型为a
时,返回总是为Car
,当为b
时,类型为Bike
。
这可能吗?
东西very close:
// @flow
const items = [1, 2, 3];
type FirstType = ((_: 'a') => number) & ((n: 'b') => Array<number>);
const first: FirstType = (n):any => {
if (n === "a") {
return items[0];
} else if(n === 'b') {
return items;
}
}
const a: number = first('a');
const b: Array<number> = first('b');
感谢
使用[泛型](https://flow.org/en/docs/types/generics/)? –
泛型仅在输入与输出类型相同时才起作用。在这种情况下,输入是一个字符串“a”,输出是一个对象。输入和输出之间的映射必须在'fn'中完成,而不是在父项中完成,因为父项无法知道如何匹配。 –