Closed
Description
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.