为类型定义一个明确的接口或类型声明,以便编译器知道应该使用哪些属性。例如,
interface User {
username: string;
email: string;
}
function getUserInfo(key: keyof User): string {
const user: User = {
username: "John",
email: "john@example.com",
};
return user[key]; // 不会再出现警告
}
console.log(getUserInfo("username")); // "John"
console.log(getUserInfo("email")); // "john@example.com"
这里我们先定义了一个名为User的接口,它描述了用户的属性。同时我们还定义了一个接收key参数并返回字符串类型的函数getUserInfo,将User接口中的属性用作索引。 通过使用keyof操作符,我们可以确保在索引user时只使用User接口中已定义的属性名称。这样就可以消除警告。