xcatliu / typescript-tutorial

TypeScript 入门教程
https://ts.xcatliu.com
10.44k stars 1.33k forks source link

范型约束的最后一个例子,“多个类型参数之间也可以互相约束“这个例子T,U里面的参数问题 #141

Closed leslylulu closed 4 years ago

leslylulu commented 4 years ago

不知道是不是我理解有问题 问题:范型约束的例子 T里面有a,b,c,d, U 里面有b,d T为什么还要去继承U ???

xcatliu commented 4 years ago

为了强制要求 copyFields 的第二个参数中不能出现一个其他的第一个参数中不存在的字段:

function copyFields<T extends U, U>(target: T, source: U): T {
    for (let id in source) {
        target[id] = (<T>source)[id];
    }
    return target;
}

let x = { a: 1, b: 2, c: 3, d: 4 };
copyFields(x, { b: 10, e: 20 });
// Property 'e' is missing in type '{ a: number; b: number; c: number; d: number; }' but required in type '{ b: number; e: number; }'.(2345)

https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=10&pc=33#code/GYVwdgxgLglg9mABBOAHAngMRgUwDYAmAzgDwAqiOAHlDmMYgKoA0TAfABRQCGATgOY4oALkRlWROCF4QcoxgEpRFAN4BYAFCJtiYHF6IOeIYhgFTSSdNkLE6rTsc8BQgNpmAuogC8h8mysZHAV3Ag8Abk1HAF8onV4haSRnQShIjViNTWMoRCofO0RuUQBGVgAjUQAmVghRAGZWAlEAFkRo9M0UDGx8Yg4qVhVESsQSgAZWOUQq8faFcKA

leslylulu commented 4 years ago

这么一说就明白了,谢谢指教