문제

In my TypeScript app, I'm using a library function (written in JavaScript), which can return either a string (for 1 result) or string[] (for several). Is there a way to represent this in TS without falling back on any?

At the moment I'm just using values: string[] but that doesn't properly represent the possibility of a scalar result.

도움이 되었습니까?

해결책

As of TypeScript 1.0, there is no simple way for modeling a function that has varied return types that are not compatible (you can define an interface For example that returns objects that share a common base type, but an array and a string do not).

You'll need to use any to represent the returned values.

You might follow and vote up this on CodePlex which is a suggestion to implement something like a Type Union.

다른 팁

You can only do that if the type or number of arguments passed in control what the output will be. This is because TypeScript supports function overloading. For example :

declare function a():number;
declare function a(f:number):number[];


var foo = a(); // number
var bar = a(123); // number[]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top