Alwaysblue
Alwaysblue

Reputation: 11830

Typescript function define multiple return type

Hey I am new to typescript and I have function which either returns an object or an array

const workspace = (workspace: string)  => {

How Can I define a return type for the same

const workspace = (workspace:string): Array | Object => {

is giving following error

Generic type 'Array<T>' 

I don't know in advance the structure of the Array and also I am not sure if this is Array | Object or not.

Upvotes: 0

Views: 2121

Answers (4)

Maciej Sikora
Maciej Sikora

Reputation: 20132

Array is not a type but type constructor, Array<SomeType> is a type, that is why you cannot say something returns type constructor, it needs to return specific type. If your function is polymorphic and can work with any array you can pass type generic argument to Array type constructor. Consider following code:

const workspace = <T>(workspace:string): Array<T> | Object => { ...

Thanks to that you return of workspace will have specific type applied.

You can also just pass unknown or any if elements are not needed to be known:

const workspace = (workspace:string): Array<any> | Object => { ...

One more explanation about type constructors. Every type definition which is requiring another type as argument is a type constructor, you can think about that as function on types. Consider example:

type AConstructor<T> = {a: T} // type constructor
type A = AConstructor<string> // evaluates to type {a: string}

Upvotes: 2

Rahul Dudhane
Rahul Dudhane

Reputation: 554

You can use any if you don't know what type of data it will return.

const workspace = (workspace:string): Array<any> | Object => {}

-----------------Extra Note------------------

You can use typescript's way to define a function. Please refer following code:

workspace(workspace: string): Array<any> | object {
                //your code here
                // your code here
              }

Upvotes: 0

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10127

Well, Array type is generic, you need to say array of what you're returning.

const workspace = (workspace:string): Array<SomeType> | Object => { }

If you really don't know the type of the elements in the array, you need to use unknown.

const workspace = (workspace:string): Array<unknown> | Object => { }

Also check this answer to find the difference between Object and object: Difference between 'object' and {} in TypeScript

You probably wanted object.

Upvotes: 1

Sam
Sam

Reputation: 548

Try

Array<String>;

if type cant be determined use <any>

Upvotes: 0

Related Questions