我使用创建了一个新的反应项目
npx create-react-app . --template typescript
它生成了package.json
和tsconfig.json
。
我进一步丰富了它们,包括 typescript-eslint
插件、eslint-plugin-jsdoc
和 eslint-config-google
.
以下是我生成的文件:
package.json
{
"name": "test",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.12",
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.10",
"@typescript-eslint/eslint-plugin": "^5.52.0",
"@typescript-eslint/parser": "^5.52.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-jsdoc": "^40.0.0",
"node-sass": "^7.0.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.8.1",
"react-scripts": "5.0.1",
"typescript": "^4.9.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"plugins": [
"@typescript-eslint",
"jsdoc"
],
"extends": [
"react-app",
"react-app/jest",
"plugin:jsdoc/recommended",
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"google"
],
"rules": {
"@typescript-eslint/no-explicit-any": 2,
"jsdoc/require-returns": 0,
"jsdoc/check-tag-names": 0,
"padded-blocks": 0
}
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"strictNullChecks": true,
"strictPropertyInitialization": true,
"noImplicitAny": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
},
"include": [
"src"
]
}
我希望在此之后,打字稿编译器的任何隐式 any
推断都会引发错误,但是当 apiService.ts
的类型被推断为 response.json()
any
文件中的以下方法不会抱怨
try {
const response =
await fetch('some-url');
if (response.ok) {
const jsonResult = await response.json(); // This is being inferred as 'any'.
return jsonResult?.categories;
}
throw Error('Fetching failed');
} catch (error) {
console.error(error);
return [];
}
我在这里错过了什么?
谢谢