Search code examples
genericstypescripttypescript2.0object-literal

Can you declare a object literal type that allows unknown properties in typescript?


Essentially I want to ensure that an object argument contains all of the required properties, but can contain any other properties it wants. For example:

function foo(bar: { baz: number }) : number {
    return bar.baz;
}

foo({ baz: 1, other: 2 });

But this results in:

Object literal may only specify known properties, and 'other' does not exist in type '{ baz: number; }'.

Solution

  • Well, i hate answering my own questions, but the other answers inspired a little thought... This works:

    function foo<T extends { baz: number }>(bar: T): void {
        console.log(bar.baz);
    }
    
    foo({baz: 1, other: 2});