首页 > 解决方案 > 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,当对象被前一个函数动态修饰时?

标签: typescript

解决方案


你可以只使用接口而不是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

这应该防止使用缺少函数所需参数的输入调用函数。不确定这是否是您所追求的。


推荐阅读