Вопрос

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