Dynamic type checking against interface in typescript

Viewed 27
export function createListItems<T>(data:any[]): T[]{
    const items: T[] = [];
    for (let i = 0; i < data.length; i++) {
        let obj: Partial<Record<keyof T,string | number >>={};//must have age and name, string and number type 
          Object.keys(data[i]).map((key:string) => {
              obj[key]=data[i][key];//taking address as well and boolean type as well
          });
          items.push(obj as T);
        
    }
    return items;
}

interface userDetails{
  name:string;
  age:number;
}


console.log(createListItems<userDetails>([{name:true,address:false},{name:"kailash",age:"string"}]);

In the above code obj should take only name and age but taking address property as well. It should accept only string and number types but accepting boolean type also. I want name should be of type only string and age should be of type only number. But for name property it is taking even boolean value as well dynamically. How can I check if dynamic key exists in interface or not and it value is matching with the type as it is defined in interface?

1 Answers

When you say let obj: Partial<Record<keyof T,string | number >>={} you are saying that obj will be a Record where the keys are the keys of T and the values are strings or numbers. However, you declared the function to take an array of type any. Type any is not a real type, it's more like a flag that says "disable all type checking for this thing", so when you are iterating through data, the values from it are also all of type any, so TypeScript trusts that the type is correct.

If you want the function to only accept items with that type, then you need to declare that in the arguments to the function with something like function createListItems<T>( data: Partial<T>[] ): T[]. If you actually want the argument to accept any and only return T[] then it's up to you to ensure that the types are correct, TypeScript can help you with that if you use type any which is effectively telling it not to help you.

Related