Home > Blockchain >  How to return the property of an interface for a specific type in TypeScript?
How to return the property of an interface for a specific type in TypeScript?

Time:12-11

I need to return the properties of an interface only for a specific type. I created this example to explain it better:

interface IPerson {
  name: string;
  age: number;
  city: string;
  hasDriverLicense: boolean;
}

let people: IPerson[] = [];

people.push({name: "John", age: 20, city: "Honolulu", hasDriverLicense: false});
people.push({name: "Mary", age: 25, city: "Rio de Janeiro", hasDriverLicense: true});
people.push({name: "Stuart", age: 30, city: "Dubai", hasDriverLicense: true});

How do I return, for example, only string-type properties of the variable?

// Expected result:
[{
  "name": "John",
  "city": "Honolulu",
}, {
  "name": "Mary",
  "city": "Rio de Janeiro",
}, {
  "name": "Stuart",
  "city": "Dubai",
}]

Are there any methods that allow me to specify the type of property I need? Or would it be necessary to go further and create a function with some ifs?

CodePudding user response:

As this article says you could define a type definition that picks only the keys you want for your definition.

Here is the type:

type SubType<Base, Condition> = Pick<Base, {
    [Key in keyof Base]: Base[Key] extends Condition ? Key : never
}[keyof Base]>;

Here is how you can use it:

const result: SubType<IPerson, string> = {city: "Whatever", name: "Whatever"} // only city and name can be added.

CodePudding user response:

You have to write your own method for it. For example:

function extractDataBasedOnDataType(arr: any[], type: string) {
    let newArr = arr.slice();
    return newArr.map((item: any) => {
        Object.keys(item).forEach((key: string) => {
            if (typeof item[key] !== type) {
                delete item[key];
            }
        });
        return item;
    });
}

The above code will only work for basic data types because typeof only works for basic types.

  • Related