Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
leslylulu opened this issue Jun 4, 2020 · 2 comments

Comments

@leslylulu
Copy link

leslylulu commented Jun 4, 2020

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

@xcatliu
Copy link
Owner

xcatliu commented Jun 5, 2020

为了强制要求 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

@xcatliu xcatliu closed this as completed Jun 5, 2020
@leslylulu
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants