MST
星途 面试题库

面试题:TypeScript中实现简单反射功能

在TypeScript中,假设有一个类`Person`,包含属性`name`和`age`。请编写代码实现一个简单的反射功能,能够根据属性名获取对象的属性值。
31.2万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
class Person {
    name: string;
    age: number;
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}

function getPropertyValue<T, K extends keyof T>(obj: T, propertyName: K): T[K] {
    return obj[propertyName];
}

// 使用示例
const person = new Person('Alice', 30);
const nameValue = getPropertyValue(person, 'name');
const ageValue = getPropertyValue(person, 'age');

console.log(nameValue); 
console.log(ageValue);