问题
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; }'.
回答1:
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 });
回答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});
回答3:
This can be most easily accomplished by defining your object before the function call:
function foo(bar: { baz: number }) : number {
return bar.baz;
}
const obj = { baz: 1, other: 2 };
foo(obj);
回答4:
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>
来源:https://stackoverflow.com/questions/42723922/can-you-declare-a-object-literal-type-that-allows-unknown-properties-in-typescri