Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

typescript 类型推导的问题

能正常推导的例子

function createStore<
  R,
  E extends Record<string, (arg: R) => void>
>(reducers: R, effects: E) {}

createStore(
  {
    hello() {},
  },
  {
    world(arg) {
      // 这里能自动推导 arg: { hello(): void }
      arg.hello();
    },
  },
);

我封装库需要写成以下参数形式

function createStore<
  R,
  E extends Record<string, (arg: R) => void>
>(store: { reducers: R; effects: E }) {}

createStore({
  reducers: {
    hello() {},
  },
  effects: {
    world(arg) {
      // 这里无法推导 TS2571: Object is of type 'unknown'.
      arg.hello();
    },
  },
}); 

有没有办法让下面这种 store 对象参数形式也支持类型自动推导?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

解决了

function createStore<R, E extends Record<string, (arg: R) => void>>(store: {
  reducers: R;
  effects: E;
}) {}

createStore({
  reducers: {
    hello: () => {},
//  ^^^^^^^^^^^^^^^^
  },
  effects: {
    world(arg) {
      arg.hello();
    },
  },
});

这里必须是箭头函数,并且函数的参数必须表明类型。这算 ts 的 bug 吗


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...