接口类型变量/泛型变量引用当前类

时间:2021-02-03 08:47:50

标签: typescript typescript-typings

通常情况下,我想在接口定义中引用实现类,例如

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "./node_modules/.bin/nodemon src/app.js --exec npm run lint && node",
    "lint": "./node_modules/.bin/eslint **/*.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "nodemon": "^2.0.7"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^4.14.1",
    "@typescript-eslint/parser": "^4.14.1",
    "eslint": "^7.18.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-config-standard": "^16.0.2",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-vue": "^7.5.0"
  }
}

                                     

                                                                                                                                                                                                

实现这个的类看起来像

interface Clonable<T> {
   clone() : T;
}

足够好但令我恼火的是,通用变量 class C implements Clonable<C> { clone() : C { // do something and return a new C object } } 的使用所传达的含义比我希望的更广泛。 IE。可能会错误地执行此操作,例如:

T

这就是问题所在:泛型参数 class C implements Clonable<B> { clone() : B { // actually returns a new B and not a new C. Violates interface author's intention but still typechecks! } } 太宽泛了,在进行类型检查时可能会被错误地使用。

是否有另一个变量只引用实现类?或者一种将 T 限制为仅此的方法?

0 个答案:

没有答案
相关问题