Can you declare a object literal type that allows unknown properties in typescript?
Yes, you can. Try this:
interface IBaz {
baz: number;
[key: string]: any;
}
function foo(bar: IBaz) : number {
return bar.baz;
}
foo({ baz: 1, other: 2 });
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});
If the known fields are coming from a generic type the way to allow wildcards is with T & {[key: string]: unknown}
, any fields that are known must fit with the type's constraints and other fields are allowed (and considered type unknown
)
Here is a sample:
type WithWildcards<T> = T & { [key: string]: unknown };
function test(foo: WithWildcards<{baz: number}>) {}
test({ baz: 1 }); // works
test({ baz: 1, other: 4 }); // works
test({ baz: '', other: 4 }); // fails since baz isn't a number
Then if you have a generic type T
you can allow wildcard fields with WithWildCards<T>