[英]How to type annotate the constructor of "this" in Javascript with FlowType
[英]How to define a type of return based on an argument string? Flowtype javascript
例如,我得到這個fn:
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
。 我想強制執行以下操作:當類型為a
,返回值始終為Car
類型,而當類型b
為Bike
。
這可能嗎?
很接近的東西:
// @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');
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.