typescript - typescript 官方文档中的交集类型示例不起作用
问题描述
typescript官方文档中交集类型的示例代码不起作用。
我正在学习打字稿,并在Playground 编辑器中输入交集类型的示例代码,我得到了一些错误提示。如下图所示:
如何修复它们?
----- 再次更新 ------
推荐的如下,更多细节可以在评论中找到!
function extend<First extends object, Second extends object>(first: First, second: Second): First & Second {
const result: Partial<First & Second> = {};
for (const prop in first) {
if (first.hasOwnProperty(prop)) {
(result as unknown as First)[prop] = first[prop];
}
}
for (const prop in second) {
if (second.hasOwnProperty(prop)) {
(result as unknown as Second)[prop] = second[prop];
}
}
return result as unknown as First & Second;
}
class Person {
constructor(public name: string) { }
}
interface Loggable {
log(name: string): void;
}
class ConsoleLogger implements Loggable {
log(name: string) {
console.log(`Hello, I'm ${name}.`);
}
}
const jim = extend(new Person('Jim'), ConsoleLogger.prototype);
jim.log(jim.name);
解决方案
像这样:
// hasOwnProperty is part of "object", so we specify the Generic needs to be a subtype of Object - or rather a "non-primitive" type.
function extend<First extends object, Second extends object>(first: First, second: Second): First & Second {
const result: Partial<First & Second> = {};
for (const prop in first) {
if (first.hasOwnProperty(prop)) {
// TypeScript suspects an error here, that's why we need to convert to unknown first
(result as unknown as First)[prop] = first[prop];
}
}
for (const prop in second) {
if (second.hasOwnProperty(prop)) {
(result as unknown as Second)[prop] = second[prop];
}
}
return result as unknown as First & Second;
}
class Person {
constructor(public name: string) { }
}
interface Loggable {
log(name: string): void;
}
class ConsoleLogger implements Loggable {
log(name: string) { // Implicit any, we know it needs to be of type "string" though, so we can just type it
console.log(`Hello, I'm ${name}.`);
}
}
const jim = extend(new Person('Jim'), ConsoleLogger.prototype);
jim.log(jim.name);
推荐阅读
- python - Pandas:将 DF 拆分为多个 csv
- html - 按钮文本未居中
- typescript - 如何使用包含泛型参数的泛型约束?
- kubernetes - 当 NFS PVC 变得不可用时,Kubernetes pod 挂起
- arrays - Golang Unmarshall 嵌套 JSON 中的特定对象
- jquery - 修复了可调整大小的 HTML 表格上的标题,包括自动水平滚动溢出
- android - Firebase 没有将 OTP 发送到移动设备——Android Studio firebase 手机身份验证错误
- python - t-test 模块问题 python
- reactjs - 将 React-native-art Surface 转换为 Image 或 base64
- ios - 为什么我们应该使用表格视图或集合视图而不是滚动视图?