typescript - TypeScript - 将装饰对象的类型设置为函数参数
问题描述
我有以下非常做作的示例:
https://codesandbox.io/s/wonderful-nobel-xv0ss?file=/src/index.ts
const barFunc = (ctx: any) => {
const bar = ctx.bar;
console.log(bar);
ctx.baz = "baz";
return ctx;
};
const fooFunc = (ctx: any) => {
const foo = ctx.foo;
const baz = ctx.baz;
console.log(foo, baz);
return ctx;
};
const funcs = {
foo: fooFunc,
bar: barFunc
};
const ctx = {
foo: "foo",
bar: "bar"
};
const b = funcs.bar;
b(ctx);
const f = funcs.foo;
f(ctx);
里面fooFunc
很高兴知道baz
存在于ctx
,我该怎么做?
一般来说,如何设置函数参数类型,即。ctx
,当对象被前一个函数动态修饰时?
解决方案
你可以只使用接口而不是any
类型吗?IE
interface IHazBaz {
baz: string;
}
interface IHazBar extends IHazBaz {
bar: string;
}
interface IHazFoo extends IHazBaz {
foo: string;
}
const barFunc = (ctx: IHazBar) => {
const bar = ctx.bar;
console.log(bar);
ctx.baz = "baz";
return ctx;
};
const fooFunc = (ctx: IHazFoo) => {
const foo = ctx.foo;
const baz = ctx.baz;
console.log(foo, baz);
return ctx;
};
const funcs = {
foo: fooFunc,
bar: barFunc
};
const ctx = {
foo: "foo",
bar: "bar"
};
const b = funcs.bar;
b(ctx); // type error
const f = funcs.foo;
f(ctx); // type error
这应该防止使用缺少函数所需参数的输入调用函数。不确定这是否是您所追求的。
推荐阅读
- css - AngularJS Symfony 2 自动生成 CSS
- javascript - CSP 中源“未定义”的脚本是什么意思?
- inkscape - Inkscape:使同一路径的两个段平行或垂直
- angularjs - AngularJS 中的双重 ng-view/ui-view,有可能吗?
- javascript - javascript中的日期验证器
- javascript - 当我将文件上传到 iis7 时,文件被截断
- php - 根据 varchar 值更新 DB(MySQL)
- c# - EasyPost USPS - 如何购买 Media Mail 货件?
- php - 通过 Ajax 将搜索词和自定义标志发送到 php 函数
- c# - 我需要在读取文件时忽略特定行