如何解决如何在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
我们可以使用以下方法解决此问题,但是问题是,每当我们向maths命名空间添加新方法时,建议将其添加到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:
还有什么方法可以将这种类型转发给react组件?这样当我们从道具访问它时,它应该显示所有这些功能的列表吗?
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 });
};
注意:不要使用名称空间,现代模块通常是更好的解决方案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。