【发布时间】:2018-10-04 22:33:49
【问题描述】:
为什么 TypeScript 类型检查器允许带有与定义不严格匹配的函数参数的 prop?
具体来说,我定义了一个函数callbackImpl = (str: string): number,并将其作为定义为callback(parameter: string | undefined): number; 的React prop 参数提供,这出乎意料地有效。
这对我来说是不直观的,在我看来非常危险!
但是!调用callbackImpl(undefined) 是行不通的,我认为这是正确的。
一个完整的例子:
import React from "react";
interface Props {
callback(parameter: string | undefined): number;
}
class A extends React.Component<Props> {
componentDidUpdate() {
this.props.callback(undefined);
}
}
class B extends React.Component {
private callbackImpl = (str: string): number => {
// Will crash if str is undefined
return str.length;
};
// THIS IS NOT ALLOWED! And rightly so!
private callLocalWithUndefined() {
// TS2345: Argument of type 'undefined' is not assignable to parameter of type 'string'.
this.callbackImpl(undefined);
}
render() {
return (
<React.Fragment>
<A
// This is obviously just as illegal as what happens in callLocalWithUndefined,
// since callbackImpl explicitly does not accept undefined as the first parameter,
// but no type errors here!?
callback={this.callbackImpl}
/>
</React.Fragment>
);
}
}
我在tsconfig.json中设置了"strict": true,
这是一个更完整的tsconfig.json 列表,省略了一些本地内容。
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"moduleResolution": "node",
"module": "esnext",
"allowSyntheticDefaultImports": true,
"target": "es6",
"jsx": "react",
"allowJs": true,
"strict": true,
"noEmitOnError": true,
"plugins": [],
"baseUrl": "./",
"paths": {
// Omitted
},
"lib": [
"es2017", // Object.entries support
"dom"
],
"types": ["gapi", "gapi.auth2", "node"]
},
"exclude": [
"node_modules"
]
}
我做错了吗?我的 tsconfig 设置错了吗?我是不是误会了什么?
谢谢!
编辑
Titian Cernicova-Dragomir 回答后的其他资源
- Strict Function Types 如 TS 2.6 发行说明所述。描述严格函数类型检查未涵盖的方法。
【问题讨论】:
-
我更新了答案以反映添加的代码。
标签: reactjs typescript