我们正在寻找一种使用Object.assign的类型安全的方法.但是,我们似乎无法使其发挥作用.
为了显示我们的问题,我将使用Generics文档中的copyFields方法
function copyFields<T extends U, U>(target: T, source: U): T {
for (let id in source) {
target[id] = source[id];
}
return target;
}
function makesrc(): Source { return {b: 1, c: "a"}}
interface Source {
a?: "a"|"b",
b: number,
c: "a" | "b"
}
Run Code Online (Sandbox Code Playgroud)
我希望引擎阻止我创建未声明的属性
/*1*/copyFields(makesrc(), {d: "d"}); //gives an error
/*2*/copyFields(makesrc(), {a: "d"}); //gives an error
/*3*/copyFields(makesrc(), {c: "d"}); //should give an error, but doesn't because "a"|"b" is a valid subtype of string.
//I don't …Run Code Online (Sandbox Code Playgroud) typescript ×1