假设我们的 TypeScript 代码如下所示:
type User = {
id: number,
name: string,
}
let user1: User = {id: 123, name: "Hello"};
let user2: User = {id: 456, name: "World"};
let keys: (keyof User)[] = ["id", "name"];
for (let key of keys) {
user1[key] = user2[key];
}
这给出了错误
Type 'string | number' is not assignable to type 'never'.
对于声明
user1[key] = user2[key];
如果我们改变keys
to的定义
let keys: string[] = ["id", "name"];
错误消失了,但我们失去了类型安全。
有什么方法可以避免这个错误,同时仍然保持类型安全?