打字稿通用方法

时间:2019-07-26 19:58:45

标签: typescript react-native

我对通用方法有疑问。此方法无法在react-native中编译:

export default function of<T>(support: Support<T>, invoke: Invoke<T>): Renderer<T> {
    return new Renderer<T>(support, invoke);
}

我遇到的错误:

bundling failed: SyntaxError: /path/Renderer.tsx: Unexpected token, expected "(" (25:26)

> 25 | export default function of<T>(support: Support<T>, invoke: Invoke<T>): Renderer<T> {
     |                           ^
  26 |     return new Renderer(support, invoke);
  27 | }

package.json

  "dependencies": {
    "fast-csv": "^3.1.0",
    "react": "16.8.6",
    "react-native": "0.60.3",
    "react-native-fs": "^2.14.1"
  },
  "devDependencies": {
    "@babel/core": "^7.5.0",
    "@babel/runtime": "^7.5.0",
    "@react-native-community/eslint-config": "^0.0.3",
    "@types/node": "^12.6.8",
    "@types/react": "^16.8.23",
    "@types/react-native": "^0.60.0",
    "babel-jest": "^24.1.0",
    "jest": "^24.1.0",
    "metro-react-native-babel-preset": "^0.54.1",
    "react-native-typescript-transformer": "^1.2.12",
    "react-test-renderer": "16.8.6",
    "tslint": "^5.18.0",
    "tslint-eslint-rules": "^5.4.0",
    "tslint-react": "^4.0.0",
    "tslint-react-recommended": "^1.0.15",
    "typescript": "^3.5.3"
  },

tsconfig.js

"compilerOptions": {
    "baseUrl": "./src",                      
    "target": "es6",
    "module": "commonjs", 
    "jsx": "react", 
    "outDir": "./dist",
    "strict": true,
    "moduleResolution": "node", 
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true, 

如果您能指出我如何解决此问题,那就太好了。

1 个答案:

答案 0 :(得分:0)

Typescript 2.9增加了支持,以便为tsx标记显式指定type参数

对于of,由于类型不是对象而生成错误。

您可以使用此

export default const OF = <T extends object>(support: Support<T>,invoke: Invoke<T> & { Renderer<T> } ) => {
    return new Renderer<T>(support, invoke);
}