[英]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?或者是否有必要进一步 go 并创建一个带有一些
if
s 的 function?
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.上面的代码只适用于 基本数据类型,因为 typeof 只适用于基本类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.