Home > other >  conditonal function typing in a object {typescript}
conditonal function typing in a object {typescript}

Time:08-21

how do i do conditonal function typing in an object?

let obj = {
 function myfunc (input: string): number;
 function myfunc (input: number): string;
 myfunc: function (input: string|number):string|number {
  ...
 }
}

does not work, it gives me syntax errors and i've tried multiple methods too but they all gave syntax errors

some examples of my attempt:

let obj = {
 myfunc (input: string): number;
 myfunc (input: number): string;
 myfunc: function (input: string|number):string|number {
  ...
 }
}
let obj = {
 function myfunc (input: string): number;
 function myfunc (input: number): string;
 myfunc: function (input: string|number):string|number {
  ...
 }
}
let obj:{
    function myfunc (input: string) : number;
    function myfunc (input: number) : string;
    myfunc: (input: string|number) => number|string
} = {
    myfunc: function (input: string|number):string|number {
        return ""
    }
}

CodePudding user response:

The following would do the trick. The problem was declaring the type definition inside the object. Just split it out as a new interface type and you're good to go.

interface MyObj {
  myfunc (input: string): number;
  myfunc (input: number): string;
}


let obj: MyObj = {
  myfunc: (input: any): any => {
    return 1;
  }
}
  • Related