首页 > 解决方案 > 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);

标签: typescript

解决方案


像这样:

// 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);

推荐阅读