autumn_smile 2018-04-10 08:15 采纳率: 0%
浏览 4096
已结题

关于TypeScript泛型对象参数问题

图片说明
deepCopy2(source: T, target?: T): T {
target = target || new source.constructor();
for ( const i in source) {
if (typeof source[i] === 'object') {
target[i] = (source[i].constructor === Array) ? [] : new source[i].constructor();
this.deepCopy2(source[i], target[i]);
} else {
target[i] = source[i];
}
}
return target;
}

new source.constructor()和new source[i].constructor();报错
TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

其类型缺少调用或构造签名的表达式无法使用 "new"
但是如果用any代替泛型就不会报错,但是如果一定要用泛型怎么解决这个问题????

  • 写回答

3条回答 默认 最新

  • threenewbee 2018-04-10 13:01
    关注
     function deepCopy2<T>(source: T, target?: {  new(...args: any[]): T }): T {
    
    评论

报告相同问题?