liumingyi1

typescript 类型推导的问题

  •  
  •   liumingyi1 · Jan 12, 2021 · 2475 views
    This topic created in 1954 days ago, the information mentioned may be changed or developed.

    能正常推导的例子

    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 对象参数形式也支持类型自动推导?

    1 replies    2021-04-16 17:38:02 +08:00
    youmoo
        1
    youmoo  
       Apr 16, 2021
    后一个 createStore 之所以报错,是因为它无法推导出 R 的实际类型,我发现这样调用就行了:

    ```js
    createStore({
    reducers: {
    hello() { },
    } as const,
    effects: {
    world(arg) {
    arg.hello();
    },
    },
    });
    ```

    https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABBATgUwIZTQZSndAHgChFEAlAGlMQFFE0APbMAEwGcK0IDXD2oKGGADmlRAAoMKEQC4KASkQBeAHyIAbnBitVxVRIEE08gN6J0rEBDQp288gG4GwYNyj26iAL5Lz34kDUTGw8YwlTGktrW09IsjIACzQAGxS4CT8fajJvRAxOHjABHJc3aDiaMgB3AhTWKRk-KoTpEQA6ZLSMhUcW71KB4l8+oA
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3086 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 11:49 · PVG 19:49 · LAX 04:49 · JFK 07:49
    ♥ Do have faith in what you're doing.