![](/img/trans.png)
[英]Typescript generics, infer object property type without a function call
[英]How to type a function that add a property with generics in typescript?
考虑这个函数:
export function addAge(obj) {
Object.defineProperty(obj, 'age', {
value: null,
});
return obj;
}
我可以在打字稿中使用泛型来知道我将使用新属性返回参数的对象吗?
像这样使用:
interface IPerson {
name: string;
}
const person: IPerson = { name: 'Juan' };
const result = addAge<IPerson>(person);
// result.age // number | null
// result.name // string
您确实可以在obj
的类型T
中使addAge
泛型,并返回一个值,该值是T
与{ age: number | null }
的交集。 { age: number | null }
或您要添加的任何属性类型:
function addAge<T>(obj: T) {
Object.defineProperty(obj, 'age', {
value: null,
});
return obj as T & { age: number | null };
}
请注意,我必须使用类型断言来告诉编译器obj
实际上有一个新属性; Object.defineProperty()
的调用签名不会改变其输入的类型,因此编译器不知道obj
不是函数末尾的T
。
(旁白:这里的实际代码使age
在运行时成为只读属性,尽管{age: number | null}
意味着您应该能够设置该属性并获取它。您可以使用{readonly age: number | null}
代替,或者您可以只使用Object.defineProperty()
以便该属性是可写的,或者任何数量的其他设置属性的方法。不过,我会考虑任何这些超出问题的范围。)
无论如何,我们现在可以测试它:
const result = addAge(person);
/* const result: IPerson & {
age: number | null;
} */
console.log(result.name.toUpperCase()); // "JUAN"
console.log((result.age ?? 0).toFixed(2)); // "0.00"
看起来挺好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.