David David - 3 months ago 24
TypeScript Question

Allow object literal, prevent string

The following works:

class Foo {
public bar(param: {}): void {

}
}

let foo: Foo = new Foo();
foo.bar(""); // Ok
foo.bar({test: ""}); // Also Ok


Is it possible to change the method signature of
bar
so that:

foo.bar({somePropertyWhichIdontKnowTheName: ""}); // Would be ok
foo.bar(""); // Not Ok

Answer

Try this:

class Foo {
    public bar(param: { [key: string]: any }): void {

    }
}

Or:

type FooBarParams = {
    [key: string]: any
}

class Foo {
    public bar(param: FooBarParams): void {

    }
}

And then:

let foo: Foo = new Foo();
foo.bar(""); // Error: Argument of type 'string' is not assignable to parameter of type { [key: string]: any }
foo.bar({test: ""}); // ok
Comments