typescript泛型分配空对象

时间:2016-10-25 11:53:57

标签: typescript

这就是我想要实现的目标:

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

我收到错误TS2322:输入&#39; {}&#39;不能分配给&#39; T&#39;。

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:0)

你可以这样做:

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 {
    ...
}

这给了你同样的东西。

答案 1 :(得分:0)

除了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 to TypeScript: Intellisense and dynamic members