简体   繁体   中英

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

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 if s?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM