當然可以。你只需要用instanceof
來測試你的test
變量。 Typescript將限制類型。
type Fruit = "apple" | "orange"
function doSomething(foo: Fruit): string | string[] {
if (foo == "apple") return "hello";
else return ["hello","world"]
}
// here the type is still inferred as: string | string[]
var test = doSomething("orange");
if (test instanceof String) {
// TypeScript knows test is type: string
doSomethingWithString(test);
} else {
// TypeScript knows test is type: string[]
doSomethingWithStringArray(test);
}
function doSomethingWithString(input: string) {}
function doSomethingWithStringArray(input: string[]) {}
UPDATE
或許你只是想使通用的方法來代替。
function doSomething<T>(foo: Fruit): T {
if (foo == "apple") return "hello";
else return ["hello","world"]
}
var test1 = doSomething<string>("apple");
var test2 = doSomething<string[]>("orange");
或者另一個選擇是將反轉這樣的流動的東西:
type Fruit = "apple" | "orange"
function doSomething(foo: Fruit): void {
if (foo == "apple")
doSomthingWithString("hello");
else
doSomethingWithStringArray(["hello","world"]);
}
function doSomethingWithString(input: string) {}
function doSomethingWithStringArray(input: string[]) {}
UPDATE
其實我相信約翰·懷特的是一個更好的答案。
'test'變量類型應該是'字符串[] | string' –
@AlekseyL。我不同意。如果將''orange''作爲參數傳遞給'doSomething',則總是產生一個'string []',那麼'test'也具有這種類型是正確的。您需要使用[overloading](http://stackoverflow.com/a/39743710/2788872)。 –
@JohnWhite'doSomething'簽名清楚地表明返回類型是'string [] | string',這不是重載的情況,您只需根據特定輸入 –