Queue类报错了

来源:2-12 泛型(Generics) 第三部分 - 类和接口

linsky

2021-06-07

老师您好。运行时报错了

class Queue22<T> {
    private data = [];
    push(item: T) {
      return this.data.push(item)
    }
    pop(): T {
      return this.data.shift()
    }
  }
  
  const queue22 = new Queue22<number>()
  queue.push(1)

报错信息

/usr/local/lib/node_modules/ts-node/src/index.ts:587
    return new TSError(diagnosticText, diagnosticCodes);
           ^
TSError: ⨯ Unable to compile TypeScript:
test-g.ts:4:29 - error TS2345: Argument of type 'T' is not assignable to parameter of type 'never'.

4       return this.data.push(item)
                              ~~~~
test-g.ts:7:7 - error TS2322: Type 'undefined' is not assignable to type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'undefined'.

7       return this.data.shift()
        ~~~~~~~~~~~~~~~~~~~~~~~~

    at createTSError (/usr/local/lib/node_modules/ts-node/src/index.ts:587:12)
    at reportTSError (/usr/local/lib/node_modules/ts-node/src/index.ts:591:19)
    at getOutput (/usr/local/lib/node_modules/ts-node/src/index.ts:921:36)
    at Object.compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1189:32)
    at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1295:42)
    at Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:1298:12)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)

node: v12.20.0
tsc: v4.3.2

写回答

1回答

张轩

2021-06-08

同学你好 应该是typescript 版本问题,在这里要指定一下数组类型,我简单修改了一下,没有报错啦。

class Queue22<T> {
    private data:Array<T> = [];
    push(item: T) { return this.data.push(item) }
    pop() { return this.data.shift() }
}
    
const queue22 = new Queue22<number>()
queue22.push(1)
const poped = queue22.pop()


1
0

React18+TS高仿AntD从零到一打造组件库

设计,开发,测试,发布再到 CI/CD,从0到1造轮子

2128 学习 · 959 问题

查看课程