typescript - 如何在 TypeScript 中将函数的返回类型指定为命名空间类型,以便提出建议
问题描述
export namespace maths {
export function add(payload) {
console.log(payload);
}
export function subtract(payload) {
console.log(payload);
}
export function multiply(payload) {
console.log(payload);
}
}
export const returnNewobj = (obj, name: string) => {
return Object.assign(obj, { name });
};
const mathsFunction = returnNewobj(maths, "mathsFunction");
mathsFunction. // it doesn't suggest the function inside the mathsFunction
我希望 mathsFunction 应该显示所有可用的函数。
我们可以使用下面的方法解决这个问题,但问题是每当我们向数学命名空间添加新方法时,它不会建议,直到我们将其添加到 IMaths 接口
interface IMaths {
add: (payload: number) => string;
substract: (payload: number) => number;
}
const returnNewobj = (actions): IMaths => {
return actions;
}
const mathsFunction = returnNewobj(maths);
mathsFunction.add(10); // here it shows the suggestion but the issue is we manuly have to sync namespace and type
编辑1:
还有没有办法将这种类型转发到反应组件?这样每当我们从道具访问它时,它应该显示列出所有这些功能?
interface IAppProps {
actions: any; // how to forwarded returnNewobj type to this interface?
}
export class App extends React.Component<AppProps,AppState> {
constructor(props) {
super(props);
}
fireAction(): void {
this.props.actions. // should list all those functions which is in namespace
}
render() { return () }
}
const mapDispatchToProps = (dispatch, props) => {
return { actions: returnNewobj(maths) };
};
export default connect(null, mapDispatchToProps)(AppComponent);
解决方案
您需要进行returnNewobj
泛型以便将目标对象的类型转发到结果:
export const returnNewobj = <T,>(obj:T, name: string) => {
return Object.assign(obj, { name });
};
注意:不要使用命名空间,现代模块通常是更好的解决方案。
推荐阅读
- javascript - 在 Google 图表的图表顶部显示注释文本
- python - conda 前缀 (-p) 仍然在 home 上创建一个 .conda 目录
- android - Firebase Google 登录重新身份验证错误:提供的身份验证凭据格式错误或已过期
- c# - StorageProviderSyncRootManager UnauthorizedAccessException
- javascript - Node 的 Buffer.from(string, "binary") 的 Deno 等价物是什么?
- css - 如何修改闪亮R侧边栏中的输入属性
- sed - 协助 sed
- c# - Unity C# 中的语法错误(语法错误,预期为“,”)
- azure - 天蓝色上的公共IP地址是否仅绑定到一台虚拟机?
- php - foreach 每次迭代一次输出所有数组项