Home > Mobile >  Typescript: share types between a function params and an object properties
Typescript: share types between a function params and an object properties

Time:07-02

I'm looking for a way to share the types between a function params and an object properties.

Let me example this for you:

const f = (param1: string, param2: number, param3: boolean): any => null
const n = (obj: Array<keys and types of every f function param>): any => null

So I can call the n function in this way:

n([
  { param1: "a", param2: 1, param3: true },
  { param1: "b", param2: 2, param3: false },
])

I need to synchronize the params of the function f with the properties of the object obj.

Parameters<typeof f> is close but this returns the type [string, number, boolean] but I need { param1: string, param2: number, param3: boolean } key-value based.

CodePudding user response:

You can try other way around - type the object first, and then type your function based on the object type:

type T = {param1: string, param2: number, param3: boolean}

const f = (param1: T['param1'], param2: T['param2'], param3: T['param3']): any => null

const n = (obj: T[]): any => null

play

  • Related