xcatliu/typescript-tutorial

泛型

xcatliu opened this issue · 18 comments

看不懂啊

写的真好呀

不会TS的前端不是好程序员

是我ts版本高了吗(4.0.2),泛型类的写法不行呀,必须得加构造函数耶

看了下官网,得把tsconfig.json的strict设为false

·Property 'zeroValue' has no initializer and is not definitely assigned in the constructor.ts(2564)`
这个例子有问题啊

刚才查了下,官方文档也是错的,在stackoverflow上找到了答案

class GenericNumber<T> {
    // to get rid of  error, you can define constructor 
    // which takes [zeroValue] and [add] as arguments
        constructor(public zeroValue: T, public add: (x: T, y: T) => T){
            this.zeroValue = zeroValue;
            this.add = add;
        }
    }

function copyFields<T extends U, U>(target: T, source: U): T { for (let id in source) { target[id] = (<T>source)[id]; } return target; }
请问这段代码的(<T>source)是什么意思?这个写法没看明白

@codon19 <T>source 就是 source as T,把 source 断言成 T 类型

@codon19 <T>source 就是 source as T,把 source 断言成 T 类型

嗯好的,谢谢

努力学习

泛型后面感觉复杂化了,看不懂是解决什么问题的

有个问题,多个类型参数之间也可以互相约束:

function copyFields<T extends U, U>(target: T, source: U): T {
    for (let id in source) {
        target[id] = (<T>source)[id];
    }
    return target;
}

let x = { a: 1, b: 2, c: 3, d: 4 };

copyFields(x, { b: 10, d: 20 });

上例中,我们使用了两个类型参数,其中要求 T 继承 U。这里是不是应该写继承于?

a extends b 不是a继承于b吗?

整段话是不是可以理解为T和U要保证是相同类型的?

function copyFields<T, U extends T>(target: T, source: U): T {
  for (let id in source) {
    target[id] = (<T>source)[id];
  }
  return target;
}

换成这种形式为什么不行?

@sunq0001
刚才查了下,官方文档也是错的,在stackoverflow上找到了答案

class GenericNumber<T> {
    // to get rid of  error, you can define constructor 
    // which takes [zeroValue] and [add] as arguments
        constructor(public zeroValue: T, public add: (x: T, y: T) => T){
            this.zeroValue = zeroValue;
            this.add = add;
        }
    }

class GenericNumber {
zeroValue!: T;
add!: (x: T, y: T) => T;
}

加个! 就通过了

@allenlinc

@sunq0001
刚才查了下,官方文档也是错的,在stackoverflow上找到了答案

class GenericNumber<T> {
    // to get rid of  error, you can define constructor 
    // which takes [zeroValue] and [add] as arguments
        constructor(public zeroValue: T, public add: (x: T, y: T) => T){
            this.zeroValue = zeroValue;
            this.add = add;
        }
    }

class GenericNumber {
zeroValue!: T;
add!: (x: T, y: T) => T;
}

加个! 就通过了

@allenlinc

@sunq0001
刚才查了下,官方文档也是错的,在stackoverflow上找到了答案

class GenericNumber<T> {
    // to get rid of  error, you can define constructor 
    // which takes [zeroValue] and [add] as arguments
        constructor(public zeroValue: T, public add: (x: T, y: T) => T){
            this.zeroValue = zeroValue;
            this.add = add;
        }
    }

class GenericNumber {
zeroValue!: T;
add!: (x: T, y: T) => T;
}

加个! 就通过了

这个加!是什么语法呀

泛型的个人理解:
在泛型的结构中,T相当于类型的参数,使用时通过<type>传入具体的类型,用来替换T位置的类型。