我有以下功能:
change(key: keyof McuParams, dispatch: Function) {
/** Body removed for brevity */
}
Run Code Online (Sandbox Code Playgroud)
当我调用函数时...
this.change(VARIABLE_FROM_MY_API, this.props.dispatch)
Run Code Online (Sandbox Code Playgroud)
...我(可以理解)收到以下错误:
Argument of type 'string' is not assignable to parameter of type '"foo" | "bar"'
这是有道理的,因为编译器无法知道我的 API 在编译时发送了什么。但是,有时可以使用用户定义的类型保护在运行时推断类型信息,并通过条件将该信息传递给编译器。
是否可以为keyof字符串类型编写用户定义的类型保护,例如keyOf foo何时foo仅定义为类型(而不是在数组中)?如果是这样,如何?
这是一个例子:
interface McuParams {
foo, bar, baz;
}
function change(key: keyof McuParams, dispatch: Function) {
}
function isKeyOfMcuParams(x: string): x is keyof McuParams {
switch (x) {
case 'foo':
case 'bar':
case 'baz':
return true;
default:
return false;
}
}
function doSomething() {
const VAR_FROM_API = <string>'qua';
if (!isKeyOfMcuParams(VAR_FROM_API)) return;
change(VAR_FROM_API, () => { });
}
Run Code Online (Sandbox Code Playgroud)
在 中doSomething,您可以使用您喜欢的任何控制流块来代替return(例如if、 或throw等)。
| 归档时间: |
|
| 查看次数: |
1108 次 |
| 最近记录: |