I want to implement type-checking of function arguments, where properties of second argument are based on properties of previous one.
The config
variable should contain only such properties that are present in objects in values
array. Properties should be optional (it is not needed to have all of them in config
, but it is not allowed to add different ones.
Please, see the example code:
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 optionaly contain only "foo", "bar" properties in this example
const config = {
foo: {
highPriority: true,
callback: () => []
},
// not present in values objects
wrong: {
highPriority: true,
callback: () => []
}
};
// config should be marked with errors as "wrong" is not present in values objects
const result = customFunction(values, config);
In the last line, config
should be marked as error, because it introduces wrong
property, which is not present in original values
object.
I can force some checking with implementing an interface to the config
, however I think it's unnecessary and that it could be done without it.
interface ISpecific {
foo: any,
bar: any
}
const values: ISpecific[] = [
{
foo: 'foo',
bar: 'bar'
},
{
foo: 'foo',
bar: 'bar'
}
];
const config: Config<ISpecific> = {
// ...
// wrong property is marked as error
}
UPDATED:
config
is defined elsewhere and doesn't know aboutvalues
variablecustomFunction
is used in several places across the application so passing theconfig
as object literal is not viable.
Any help?
T
at all. If that is true, you'd be better served by making them generic in the keys (e.g.,type CustomType <K extends keyof any> = { [P in K]: number };
or more succinctlyRecord<K, number>
. Your function would then be generic inK
, whereT
if needed is replaced byRecord<K, any>
.T
. But with your first example I get error messageType 'T' does not satisfy the constraint 'string'.
config
- I'd rather want it to be the opposite -config
property names should be dependant onvalues
property names.