Rami Chasygov
Rami Chasygov

Reputation: 2784

Parameter type for multitypes in TypeScript

I wanna create type for function parameter. Pseudocode below. Explaining, what I want to reach: args could be array of objects {[name: string]: any}[] or it could be array of objects and boolean value {[name: string]: any}[] & boolean and or operator between them |, return object {[name: string]: any}, so far this code doesn't work, how I can fix it or reach same result?

const someFunc = (...args: {[name: string]: any}[] | ({[name: string]: any}[] & boolean)): {[name: string]: any} => {
  // ...
  return output;
}

Upvotes: 0

Views: 78

Answers (2)

Tyler Sebastian
Tyler Sebastian

Reputation: 9468

not quite

type SimpleObject = { [name: string]: any }

function a(...params: (SimpleObject | boolean)[]): SimpleObject {
  params.forEach(param => {
    // param is either a boolean or SimpleObject
  })

  return ...
}

{ [name: string]: any }[] & boolean doesn't really mean... anything

you don't have to declare SimpleObject separately, you can do it inline, I just find it cleaner

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138567

As you have to do typechecking afterwards, just do:

 function someFunc(...args: any[]) {
  //...
 }

Upvotes: 0

Related Questions