yes
yes

Reputation: 21

conditonal function typing in a object {typescript}

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 ""
    }
}

Upvotes: 2

Views: 39

Answers (2)

yes
yes

Reputation: 21

someone in the typescript discord gave me a solution that works very well:

let obj = {
    myfunc: (() => {
        function myfunc (input: string):number;
        function myfunc (input: number):string;

        function myfunc (input: string|number): number|string {
            let a = input // string|number
            return a
        }

        return myfunc
    })()
}

obj.myfunc(0) // string
obj.myfunc("hello") // number

Upvotes: 0

lepsch
lepsch

Reputation: 10319

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;
  }
}

Upvotes: 1

Related Questions