如果函数返回2个值,我如何描述该类型?
我的职能是:
const firstFunction = (input: number) => {
const firstValue = input;
const innerFunction = (funcInput: number) => {
funcInput * input;
};
return [firstValue, innerFunction];
};我这样叫它:
const [value, innerFunction] = firstFunction(1);当我调用innerFunction时,TypeScript不确定它是否是一个函数。现在它认为它是:
number | ((funcInput: number) => void)如何告诉TypeScript第二个返回值是一个函数?
发布于 2020-07-01 14:29:40
您需要返回一个类型才能有效地做到这一点:
const firstFunction = (input: number): [number, (funcInput: number) => void] => { ... };
// ^-----------------------------------^ 发布于 2020-07-01 14:35:29
您还可以定义一个类型/接口,为了获得更高的可读性,您将返回该类型/接口:
interface MyInterface {
myValue: number;
myFunction: number => void
}
const firstFunction = (input: number): MyInteface => { ... }; // Return will be a bit different as well还可以直接返回类型:
const firstFunction = (input: number) => {
// ...
return {
value,
innerFunction
}
};如果我没记错的话,元组的解决方案不会给你起名字,因为它是基于位置的。
这取决于您选择最佳的方法,我确实更喜欢字段的名称,以避免误解。
https://stackoverflow.com/questions/62679094
复制相似问题