Skip to content

[Proposal] Initializer syntax for function types #21572

Closed
@AlCalzone

Description

@AlCalzone

Using function types, it's possible to define types for functions with additional properties tacked on, e.g.

interface fnWithProp {
    (abc: string): string;
    foo: number;
}

In order to initialize variables of those types, one currently has to jump through hoops because the naive attempt does not work:

// Error: 
// Type '(str: any) => any' is not assignable to type 'fnWithProp'.
// Property 'foo' is missing in type '(str: any) => any'.
var abc: fnWithProp = (str) => str;
abc.foo = 7;

By explicitly casting the function to the correct type, one can avoid the error, but now TypeScript never checks if foo is assigned (even with strictPropertyInitialization = true):

var abc = ((str) => str) as fnWithProp;
console.log(abc.foo); // undefined

A working version looks like this

var abc = Object.assign(((str) => str), {
    foo: 7,
});

but abc is now being inferred as the rather cryptic type ((str: any) => any) & { foo: number }.

As an attempt to solve this problem, I propose an initializer syntax for these kinds of function types, which is similar to the object literal syntax:

var abc: fnWithProp = {
    (str) => {
        /* do something */
        return str;
    },
    foo: 7,
    /* optional: more properties */
};

or an alternative using the this keyword for the function body:

var abc: fnWithProp = {
    this: (str) => {
        /* do something */
        return str;
    },
    foo: 7,
    /* optional: more properties */
};

A usage example:

interface fnWithProp {
    (abc: number): number;
    foo: number;
}

function doSomething(transform: fnWithProp) { 
    return transform(transform.foo + 1);
}

doSomething({ this: (abc) => abc, foo: 7 });

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions