当然可以。你只需要用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',这不是重载的情况,您只需根据特定输入 –