第一题
type User = {
id: number;
kind: string;
};
function makeCustomer<T extends User>(u: T): T {
// Error(TS 编译器版本:v4.4.2)
// Type '{ id: number; kind: string; }' is not assignable to type 'T'.
// '{ id: number; kind: string; }' is assignable to the constraint of type 'T',
// but 'T' could be instantiated with a different subtype of constraint 'User'.
return {
id: u.id,
kind: 'customer'
}
}
答案:
type User = {
id: number;
kind: string;
};
// 第一种解法是修改函数返回 的类型 为 User 类型
function makeCustomer<T extends User>(u: T): User {
return {
id: u.id,
kind: 'customer'
}
}
// 第二种是解法是 修改函数返回类型为User类型的子类型
function makeCustomer<T extends User>(u: T): T {
return {
...u,
id: u.id,
kind: 'customer'
}
}