Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k 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 Reply

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 吗


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...