My function takes an array as a parameter and constructs the generic type passed in by the array. Everything is working fine, but I want to add a type check to ensure that the keys of the array match the properties of the generic type, otherwise it should throw a Typescript error.
Interfaces
interface OutputType {
id: string;
name: string;
age: number;
}
interface ArrayType {
key: string;
value: any;
}
Generic function
function TestType<T>(array: ArrayType[]): T {
let newObj = {} as T;
array.forEach((arrayItem) => {
newObj[arrayItem.key as keyof T] = arrayItem.value;
});
return newObj;
}
This should result in a TS **ERROR** because it's missing the 'id' property
const array = [
{
key: "name",
value: "TestName",
},
{
key: "age",
value: 12,
},
] as ArrayType[];
This should clear the TS error
const array = [
{
key: "id",
value: "1",
},
{
key: "name",
value: "TestName",
},
{
key: "age",
value: 12,
},
] as ArrayType[];
For the complete code example, visit:
I'm stuck on implementing a custom type for the array parameter.
I want to create a custom type to check the array being passed in and validate it against the properties of the generic type.