Skip to content

Typechecking Partial<> works differently for generic types #12751

Closed
@jauco

Description

@jauco

TypeScript Version: 2.1.1 (what's running on the playground)

Code
This works

interface Data {
    a?: "a"|"b",
    b: number,
    c: "a" | "b"
}

type Patch = Partial<Data> 
function copyFields(target: Data, source: Patch): Data {
    for (let id in source) {
        target[id] = source[id];
    }
    return target;
}

function makesrc(): Data { return {b: 1, c: "a"}}


/*1*/copyFields(makesrc(), {d: "d"}); //Should (and does) give an error
/*2*/copyFields(makesrc(), {a: "d"}); //Should (and does) give an error
/*3*/copyFields(makesrc(), {c: "d"}); //Should (and does) give an error

//I don't want to specify all the source properties 
/*4*/copyFields(makesrc(), {b: 2}); //Should not (and doesn't) give an error
/*5*/copyFields(makesrc(), {a: "b"}); //Should not (and doesn't) give an error

But the generic version doesn't

interface Data {
    a?: "a"|"b",
    b: number,
    c: "a" | "b"
}

function copyFields<T>(target: T, source: Partial<T>): T {
    for (let id in source) {
        target[id] = source[id];
    }
    return target;
}

function makesrc(): Data { return {b: 1, c: "a"}}


/*1*/copyFields(makesrc(), {d: "d"}); //Should (and does) give an error
/*2*/copyFields(makesrc(), {a: "d"}); //Should (and does) give an error
/*3*/copyFields(makesrc(), {c: "d"}); //Should (BUT DOES NOT) give an error

//I don't want to specify all the source properties 
/*4*/copyFields(makesrc(), {b: 2}); //Should not (and doesn't) give an error
/*5*/copyFields(makesrc(), {a: "b"}); //Should not (BUT DOES) give an error

I expected no change in type safety in the generic version.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions