I am looking to implement type-checking for function arguments, where the properties of the second argument are based on the properties of the previous one.
The config
variable should only contain properties present in objects within the values
array. These properties should be optional (not all required in config
, but cannot add additional ones).
Here is an example code snippet:
type CustomType <T> = {
[K in keyof T]: number
};
type Config <T> = {
[K in keyof T]? : {
highPriority: boolean;
callback: (values: any[]) => number[];
}
};
const customFunction = <T>(values: T[], config: Config <T> ): Array <CustomType<T>> => {
// logic...
return [];
};
const values = [
{
foo: 'foo',
bar: 'bar'
},
{
foo: 'foo',
bar: 'bar'
}
];
// Should optionally contain only "foo" and "bar" properties in this example
const config = {
foo: {
highPriority: true,
callback: () => []
},
// not present in values objects
wrong: {
highPriority: true,
callback: () => []
}
};
// Error should be displayed for 'config' as "wrong" property is not present in 'values' objects
const result = customFunction(values, config);
In the final line, config
must show an error because it introduces a "wrong" property that isn't present in the original values
object.
I can enforce some checking by implementing an interface for the config
, but I believe there's a way to do it without this step.
interface ISpecific {
foo: any,
bar: any
}
const values: ISpecific[] = [
{
foo: 'foo',
bar: 'bar'
},
{
foo: 'foo',
bar: 'bar'
}
];
const config: Config<ISpecific> = {
// ...
// The wrong property is marked as an error
}
UPDATED:
config
has been defined elsewhere and is not aware of thevalues
variablecustomFunction
is used in various places throughout the application, so passing theconfig
as an object literal is not feasible.
Any suggestions or assistance?