Typescript allows us to define an interface for an object that must have a key and can also allow additional keys:
interface ObjectWithTrace {
trace: string;
[index: string]: any
}
const traced: ObjectWithTrace = { trace: 'x', foo: 'bar' }; // valid
const untraced: ObjectWithTrace = { foo: 'bar' }; // Error: Property 'trace' is missing in type '{ foo: string; }' but required in type 'ObjectWithTrace'. ts(2741)
In the case above, the key trace
is necessary. We can freely add any keys to an object as long as the trace
key is included, making typescript content.
However, when trying to extend this concept to function arguments, an error arises:
type FunctionWithParamWithTrace = (args: {
trace: string;
[index: string]: any
}) => any;
const doSomethingAndTrace: FunctionWithParamWithTrace = (args: { trace: string }) => {}; // valid
const doSomethingElseAndTrace: FunctionWithParamWithTrace = (args: { trace: string, foo: 'bar' }) => {} /*
Error: Type '(args: { trace: string; foo: "bar"; }) => void' is not assignable to type 'FunctionWithParamWithTrace'.
Types of parameters 'args' and 'args' are incompatible.
Property 'foo' is missing in type '{ [index: string]: any; trace: string; }' but required in type '{ trace: string; foo: "bar"; }'.ts(2322)
*/
It seems like something is missing. Is there a way to define a type for a function that expects only one parameter - allowing any keys with any values, while also requiring a specific key to exist (e.g., a property named trace
)?
I am looking to achieve the following scenario:
const doSomethingWithTrace: FunctionWithParamWithTrace = (args: { trace: string, foo: string }) => {}; // valid
const doSomethingWithoutTrace: FunctionWithParamWithTrace = (args: { foo: string }) => {} // Error: Property 'trace' is missing in type '{ foo: string; }'...