打字稿官方文档中的交集类型示例不起作用

时间:2019-07-25 14:04:43

标签: typescript

打字稿官方文档中的intersection type示例代码无效。

我正在学习打字稿,并在Playground editor中输入交集示例代码,并得到一些错误提示。如下图所示:

enter image description here

如何修复它们?

-----再次更新------

推荐的一种如下,更多细节可以在评论中找到!

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

1 个答案:

答案 0 :(得分:1)

赞:

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