Skip to content

Instantly share code, notes, and snippets.

@crazko
Last active Jul 24, 2018
Embed
What would you like to do?
Guard argument property names
// https://stackoverflow.com/questions/50371994/typescript-type-guarding-of-argument-based-on-the-previous-one
// type CustomType <T> = {
// [K in keyof T]: number
// };
// type Config <T> = {
// [K in keyof T]? : {
// highPriority: boolean;
// callback: (values: any[]) => number[];
// }
// };
type CustomType<K extends keyof any> = {
[P in K]: number
};
type Config<K extends keyof any> = {
[P in K]?: {
highPriority: boolean;
callback: (values: any[]) => number[];
}
};
const values = [
{
foo: 'foo',
bar: 'bar'
},
{
foo: 'foo',
bar: 'bar'
}
];
// We type relative to values, no need for the extra interface
const config = {
foo: {
highPriority: true,
callback: () => []
},
bar: {
highPriority: true,
callback: () => []
},
// // will be an error
// wrong: {
// highPriority: true,
// callback: () => [K
// }
};
type NoExtraProperties<TSource, TTarget> = Exclude<keyof TSource, keyof TTarget> extends never ? true : "Extra properties detected";
const customFunction = <T, K extends keyof T, TConfig extends Config<K>>(values: T[], config: TConfig, validate: NoExtraProperties<TConfig, T>): Array<CustomType<K>> => {
// logic...
return [];
};
// Argument of type 'true' is not assignable to parameter of type '"Extra properties detected"'.
const result = customFunction(values, config, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment