【发布时间】:2021-01-03 11:42:21
【问题描述】:
我正在使用 React+TypeScript 编写我的第一个应用程序。 我很困惑为什么我的 Visual Studio 代码显示的类型检查与 CodeSandbox 中的相同代码完全不同。
这是我的 VSC 显示的内容:[props.direction as any]
这是 CodeSandbox 中的正确方式:[props.direction as FlexProps]。 链接到 Codesanbox 从我得到这个例子的地方: https://codesandbox.io/s/funny-frost-1bxwk?file=/src/Heading.tsx
当我以这种方式重写代码时,一切正常:
export const Flex = styled.div`
display: flex;
flex-direction: ${(props : FlexProps) => props.direction}
`
但是,如果接口 FlexProps 有更多类型,我将不得不在每一行分别重复它们。所以对我来说不是好方法。
我的 package.json:
{
"name": "interactive-visited-countries-map-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.11.0",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"@types/jest": "^24.0.0",
"@types/node": "^12.0.0",
"@types/react": "^16.9.0",
"@types/react-dom": "^16.9.0",
"@types/styled-components": "^5.1.2",
"@typescript-eslint/eslint-plugin": "^4.1.1",
"@typescript-eslint/parser": "^4.1.1",
"eslint": "^7.9.0",
"eslint-plugin-react-hooks": "^4.0.8",
"lodash.sortby": "^4.7.0",
"node-sass": "^4.14.1",
"normalize.css": "^8.0.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1",
"react-tooltip": "^4.2.7",
"styled-components": "^5.1.1",
"styled-icons": "^10.19.0",
"svg-url-loader": "^6.0.0",
"typescript": "^4.0.2",
"typescript-styled-plugin": "^0.15.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@types/lodash.sortby": "^4.7.6",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.4",
"prettier": "^2.1.1"
}
}
和 tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "es2015", "es2017", "dom.iterable"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": false,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"downlevelIteration": true,
"declaration": true,
"noImplicitAny": false,
"plugins": [
{
"name": "typescript-styled-plugin"
}
]
},
"include": ["src", "**/*.ts"]
}
【问题讨论】:
-
我删除了我的答案,因为我现在发现
props的类型与插件无关,所以它是错误的。我想问一下,styled的类型显示了什么?我猜它是类型any,在这种情况下你做了npm install @types/styled-components?这是对库进行类型检查所需的相关步骤。 -
我已经解决了一个问题。在 react-app-env.d 中我有 ``` ///
声明模块“styled-components”; ```我删除了声明模块“styled-components”,它似乎工作正常 -
好的,很酷,请随意发布您自己问题的答案,而不是仅仅在标题中标记“已解决”,更好地维护网站。 :) 很高兴你能解决它!
标签: reactjs typescript visual-studio-code