TypeScript 能让 React 组件实例化类型安全吗?
Can TypeScript make React component instantiation type safe?
我是 TypeScript 和 React 的新手,对于任何不正确或令人困惑的术语,我们深表歉意。基本上这就是我正在看的:
<MyComponent someNumber="40" />
someNumber
是定义为 number
的 属性,但我注意到以下行为:
- 如果我传递一个非数字值,例如
<MyComponent someNumber="foo" />
这仍然可以编译但在运行时爆炸
- 如果我没有传递任何值,例如
<MyComponent />
即使 someNumber
没有默认值,它仍然可以编译
理想情况下,这两个场景应该无法编译,但我没有找到这样做的方法。如果有帮助,我正在使用 TypeScript 2.0.6。
这是我的 tsconfig.json
:
{
"compilerOptions": {
"outDir": "./dist",
"allowJs": false,
"target": "es6",
"module": "commonjs",
"jsx": "react"
},
"include": [
"./src/**/*"
],
"files": [
"typings/index.d.ts"
]
}
如果您为组件 props 定义接口,那么编译器将为您检查所有这些:
interface MyProps {
someNumber: number;
}
interface MyState {}
class MyComponent extends React.Component<MyProps, MyState> {}
let a1 = <MyComponent someNumber={ 40 } />; // fine
let a2 = <MyComponent />; // Error: Property 'someNumber' is missing in type ...
let a3 = <MyComponent someNumber="40" />; // Error: Type 'string' is not assignable to type 'number'
编辑
问题与 OP 使用的反应定义文件有关。
使用以下方式安装定义:
npm install @types/react
问题解决了。
我是 TypeScript 和 React 的新手,对于任何不正确或令人困惑的术语,我们深表歉意。基本上这就是我正在看的:
<MyComponent someNumber="40" />
someNumber
是定义为 number
的 属性,但我注意到以下行为:
- 如果我传递一个非数字值,例如
<MyComponent someNumber="foo" />
这仍然可以编译但在运行时爆炸 - 如果我没有传递任何值,例如
<MyComponent />
即使someNumber
没有默认值,它仍然可以编译
理想情况下,这两个场景应该无法编译,但我没有找到这样做的方法。如果有帮助,我正在使用 TypeScript 2.0.6。
这是我的 tsconfig.json
:
{
"compilerOptions": {
"outDir": "./dist",
"allowJs": false,
"target": "es6",
"module": "commonjs",
"jsx": "react"
},
"include": [
"./src/**/*"
],
"files": [
"typings/index.d.ts"
]
}
如果您为组件 props 定义接口,那么编译器将为您检查所有这些:
interface MyProps {
someNumber: number;
}
interface MyState {}
class MyComponent extends React.Component<MyProps, MyState> {}
let a1 = <MyComponent someNumber={ 40 } />; // fine
let a2 = <MyComponent />; // Error: Property 'someNumber' is missing in type ...
let a3 = <MyComponent someNumber="40" />; // Error: Type 'string' is not assignable to type 'number'
编辑
问题与 OP 使用的反应定义文件有关。
使用以下方式安装定义:
npm install @types/react
问题解决了。