Skip to content

Make union function types callable. Β #57400

Closed as not planned
Closed as not planned
@ghost

Description

πŸ” Search Terms

Each member of the union type has signatures, but none of those signatures are compatible with each other, expression not callable, incompatible signatures,

βœ… Viability Checklist

⭐ Suggestion

Currently typescript does not allow executing generic functions with incompatible union type. However such behavior is not contradicting any type-safety mechanisms. As you will see from the example below there is no way to call such function without "type assertion" and there is no need for asserting the type on this phase of the programming. It would unwrap it's type based on the higher level code that will use this function and would specify the concrete needs for the exact argument types.

πŸ“ƒ Motivating Example

class Test {
    execute(a: number){
        return {
            a: 12,
            b: "hey"
        }
    }
    run(a: string){
        return{
            c: true
        }
    }
}

// As you can see the arguments 
// that will be passed to the function 
// are derived from the parameters of the function 
// thus there is no type violation

function D<T extends "execute" | "run">(arg: Test[T], value: Parameters<Test[T]>){
    arg(value) // -> error here 
                      //"Argument of type '[a: number] | [a: string]' is not assignable to 
                      // parameter of type 'never'.
                      // Type '[a: number]' is not assignable to type 'never'."
}

D<"execute">() // -> here we know already the type 
// and is narrowed enough for the argument to be the one of the same type 
// that the specific function accepts
// there is no way to mess the types and type safety is preserved

This shall be allowed in my opinion as it does not put at risk of type mismatch

πŸ’» Use Cases

  1. What do you want to use this for?
    It would allow developers to abstract away function calls and build on top of other libraries that have not taken into account the need for abstracting away common logic and fields
  2. What workarounds are you using in the meantime?
    There is no workaround currently. It is possible to narrow the type,however such a solution is not the prefered way and it polutes the codebase.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions