Skip to content

why is compile-time error occurring in the code #16884

Description

@remoteTest

The code comes from the website(http://www.typescriptlang.org/docs/handbook/advanced-types.html) :

function extend<T, U>(first: T, second: U): T & U {
    let result = <T & U>{};
    for (let id in first) {
        (<any>result)[id] = (<any>first)[id];
    }
    for (let id in second) {
        if (!result.hasOwnProperty(id)) {
            result)[id] = second[id];
        }
    }
    return result;
}

modify the code slightly:

function extend<T, U>(first: T, second: U): T & U {
    let result = <T & U>{};
    for (let id in first) {
        result[id] = first[id];
    }
    for (let id in second) {
        if (!result.hasOwnProperty(id)) {
            (<any>result)[id] = (<any>second)[id];
        }
    }
    return result;
}

Just remove the type assertion for result and first in the fourth line。
I thought that the code above will be correct,because result is defined as T & U which is considered a type containing both properties from T and U, so that accessing result[keyof T] is valid, since keyof T is assignable to keyof (T & U)。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions