【发布时间】:2015-12-13 11:07:00
【问题描述】:
我正在寻找一种转换函数或方法,它允许我保留 typescript 在结果对象上推断类型(获取类型检查和代码提示)的能力。在下面的示例中,C(和相关的 E)是被证明有问题的场景。
class Wrapper<T> {
constructor(private val: T) { }
value(): T {
return this.val;
}
}
// A
var wrappedNum = new Wrapper(1);
// Typescript infers value() and that it returns a number
wrappedNum.value().toFixed(1);
// B
var wrappedNumArray = [1, 2, 3].map(function(val) { return new Wrapper(val); });
// Typescript infers that for each element in array, value() returns number
wrappedNumArray[0].value().toFixed(1);
// C
// ** Typing of properties is lost in this transformation **
function wrapObject(obj) {
var targ = {};
for(var key in obj) {
targ[key] = new Wrapper(obj[key]);
}
return targ;
}
var wrappedObj = wrapObject({a: 1});
// Typescript does not infer the existence of `a` on wrappedObj
wrappedObj.a;
// D
// Typescript infers `a` and its type
({ a: 1 }).a.toFixed(1);
// E
// ** Typing of properties is lost in this transformation **
function noop(obj) {
return obj;
}
// Typescript does not infer the existence of `a` on noop transformed object
noop({ a: 1 }).a;
// F
function getValue() {
return { a: 1 };
}
// Typescript infers the existence of `a` and its type
getValue().a.toFixed(1);
有没有一种方法可以构建 C&E,使得类型推断可以在不知道传递的对象的结构的情况下工作?
【问题讨论】:
标签: types typescript