小编ren*_*ark的帖子

安全输入Object.assign

我们正在寻找一种使用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

5
推荐指数
1
解决办法
767
查看次数

标签 统计

typescript ×1