要按照类型迭代 TypeScript 接口的属性,可以使用 TypeScript 的 keyof 和 typeof 操作符结合循环来实现。下面是一个示例代码:
interface Person {
name: string;
age: number;
address: string;
}
const person: Person = {
name: "John",
age: 30,
address: "123 Main St",
};
// 使用 keyof 获取 Person 接口的所有属性名
type PersonKeys = keyof Person;
// 循环遍历属性名,并打印属性的类型和值
for (let key: PersonKeys in person) {
// 使用 typeof 获取属性的类型
const typeOfKey: string = typeof person[key];
console.log(`Type of ${key} is ${typeOfKey}`);
console.log(`${key}: ${person[key]}`);
}
在上面的例子中,我们定义了一个 Person 接口,包含 name、age 和 address 三个属性。然后创建了一个 person 对象,包含这些属性的具体值。
使用 keyof 操作符,我们创建了一个类型 PersonKeys,它包含了 Person 接口的所有属性名。然后使用 for 循环遍历 PersonKeys,获取属性名,并使用 typeof 操作符获取属性的类型。最后打印属性的类型和值。
运行上述代码,输出将会是:
Type of name is string
name: John
Type of age is number
age: 30
Type of address is string
address: 123 Main St
这样就实现了按照类型迭代 TypeScript 接口的属性,并打印属性的类型和值。