Typescript泛型赋值空对象



这就是我想要达到的效果:

interface IFoo { ... }
function extendWithFoo<T extends {}>(x: T = {}): T & IFoo {
 ...
}

我得到错误TS2322:类型"{}"不能分配给类型"T"。

有办法做到这一点吗?

你可以这样做:

function extendWithFoo<T extends {}>(x: T = {} as T): T & IFoo {
    ...
}

但是使用空对象是有问题的,因为它接受一切:

extendWithFoo(3); // ok
extendWithFoo("string"); // ok
extendWithFoo(true); // ok
extendWithFoo({}); // ok
extendWithFoo({ key: "value" }); // ok
extendWithFoo(new Array()); // ok

所以我的建议是使用更具体的东西。
在任何情况下,你都不是真的需要它,你可以:

function extendWithFoo<T>(x: T = {} as T): T & IFoo {
    ...
}

结果是一样的

除了Nitzan Tomer的建议之外,您还可以引入一个类型,将输入限制为仅为对象字量

type ObjectLiteral = { [key: string]: any };
interface IFoo {
    resultHasFoo(): void; 
}
function extendWithFoo<T extends ObjectLiteral>(x: T = {} as T): T & IFoo {
    return x as T & IFoo;
}
extendWithFoo(false); // error!
extendWithFoo(123); // error!
var p = extendWithFoo({
    test: "one"
});
p.resultHasFoo(); // works!

看看我的相关文章…JavaScript到TypeScript:智能感知和动态成员

最新更新