2017-08-03 106 views
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; 
} 

的问题是,回总是BikeCar 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'); 

感谢

+0

使用[泛型](https://flow.org/en/docs/types/generics/)? –

+0

泛型仅在输入与输出类型相同时才起作用。在这种情况下,输入是一个字符串“a”,输出是一个对象。输入和输出之间的映射必须在'fn'中完成,而不是在父项中完成,因为父项无法知道如何匹配。 –

回答

1

我找到了一种方法做我需要这个代码。重载函数,然后使用参数作为对象来定义返回值。相当好的解决方案,但可能会更好。

注:formatNotification参数只能是一个对象,而不是2个参数等formatNotification(type, data)

仍然不是一个好的解决方案,但中途工作。

enter image description here

而且类型:

enter image description here

相关问题