javascript - 如何在打字稿中有条件地设置函数参数类型?
问题描述
我有一个通用函数需要在 2 个地方调用
const functionA = (arg1, deleteFunction) => {
deleteFunction(arg1)
}
当我在两个不同的地方调用它时,我deleteFunction
每次都经过不同的地方。这些deleteFunctions
然后更新redux,但它们需要不同的类型,所以我收到错误
我想知道是否arg1
可以根据它包含的属性指定它应该是什么类型。像这样的东西
const functionA = (arg1: arg1.hasSomeProperty ? Arg1Types : Arg1OtherType, deleteFunction) => {
deleteFunction(arg1)
}
显然这不起作用,但 2 个 deleteFunctions 有不同的类型(一个有Arg1Types
另一个有Arg1OtherTypes
可能会以完全错误的方式进行。有任何想法吗?
解决方案
您可以使用函数重载,或者使用带有function
关键字的重载语法,或者使用带有const
箭头函数的接口,就像您的问题一样。
重载语法:
function functionA(arg: Arg1Type, deleteFunction: (arg: Arg1Type) => void): void;
function functionA(arg: Arg1OtherType, deleteFunction: (arg: Arg1OtherType) => void): void;
function functionA(arg: any, deleteFunction: (arg: any) => void): void {
deleteFunction(arg);
}
const
带有箭头函数的函数接口:
interface FunctionA {
(arg: Arg1Type, deleteFunction: (arg: Arg1Type) => void): void;
(arg: Arg1OtherType, deleteFunction: (arg: Arg1OtherType) => void): void;
}
const functionA: FunctionA = (arg: any, deleteFunction: (arg: any) => void): void => {
deleteFunction(arg);
};
在这两种情况下,如果Arg1Type
是string
和Arg1OtherType
是number
(例如),这些调用都有效:
functionA("foo", (id) => {
// ...do the deletion...
});
functionA(42, (id) => {
// ...do the deletion...
});
...而这些不会:
// Error: No overload matches this call.
// (because the types don't match)
functionA("foo", (id: number) => {
// ...do the deletion...
console.log(id);
});
// Error: No overload matches this call.
// (because no overload takes an object)
functionA({}, (id) => {
// ...do the deletion...
console.log(id);
});
在这两种情况下,IDE 等只会显示重载签名(前两个);实现签名不是。
在评论中你说:
...调用此函数如何知道要使用哪些类型?Arg1Type 和 Arg1OtherType 都是对象,但在这些对象内部,每个属性的类型不同。...我想进一步了解条件部分
TypeScript 将根据参数的类型推断要使用的正确重载。在我的示例中,类型是string
和number
。当我开始使用functionA("foo",
TypeScript 时,可以看出我正在使用string
重载,并且只允许接受字符串的函数。当我开始使用functionA(42,
TypeScript 时,我可以告诉我正在使用number
重载,并且只允许一个接受数字的函数。
对于具有不同形状的对象也可以这样:
interface Arg1Type {
prop: string;
}
interface Arg1OtherType {
prop: number;
}
functionA({"prop": "foo"}, (obj) => {
// ...do the deletion...
console.log(obj);
});
functionA({"prop": 42}, (obj) => {
// ...do the deletion...
console.log(obj);
});
推荐阅读
- python - Python SQLAlchemy 插入 paradox db
- python - 如何将 tkinter Combobox 中的选择导出到 Excel 或文本文件?
- python - Python:卡住了将字典转换为键列表和项目值
- java - 我应该使用 application.properties 还是为巨大的字段创建一个单独的文件?
- python - sqlalchemy.exc.CompileError 无法为 NullType() 生成 DDL
- javascript - 更改状态时,输入字段“继承”过去输入字段的值
- javascript - 带 saas 的暗模式
- json - 无法将表单数据发布到 Discord Webhook URL
- c++ - 如何从引导加载程序加载内核?
- docker - 错误 io_setup() failed (38: Function not implemented) in Nginx for ARM M1