2

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

2 Answers 2

1

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;
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This works for the type of the function, but inside the function definition the any allows you to do nonsense like input.magic() without any typing errors
i see, this works. I'll find a way to specify the type inside the function scope without creating a new variable for the input
i found a solution!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.