【问题标题】:How to properly type a function that is mapped back through several other objects?如何正确键入通过其他几个对象映射回来的函数?
【发布时间】:2023-02-02 16:26:42
【问题描述】:

编辑

requestedFunctionAlias 是动态的。

例如,

const getFn = ({ requestedFunctionAlias }) => {
    return FUNCTIONS_MATRIX[FUNCTION_ALIASES[requestedFunctionAlias]];
}

const fn = getFn({ requestedFunctionAlias: 'a1' });

fn({ age: 30 })

假设以下,

const myFunction1 = ({ name }: { name: string }) => console.log('name', name);
const myFunction2 = ({ age }: { age: number }) => console.log('age', age);
const myFunction3 = ({ hobbies }: { hobbies: string[] }) => console.log('hobbies', hobbies);

const FUNCTION_ALIASES = {
  a1: 'myFunction1',
  a2: 'myFunction2',
  a3: 'myFunction3',
};

const FUNCTIONS_MAP = {
  myFunction1: 'a1',
  myFunction2: 'a2',
  myFunction3: 'a3',
};


const FUNCTIONS_MATRIX = {
  [FUNCTION_ALIASES[FUNCTIONS_MAP.myFunction1]]: myFunction1,
// ^^^ Element implicitly has an 'any' type 
  [FUNCTION_ALIASES[FUNCTIONS_MAP.myFunction2]]: myFunction2,
// ^^^ Element implicitly has an 'any' type 
  [FUNCTION_ALIASES[FUNCTIONS_MAP.myFunction3]]: myFunction3,
// ^^^ Element implicitly has an 'any' type 
};

const requestedFunctionAlias: string = 'a1';

const fn = FUNCTIONS_MATRIX[FUNCTION_ALIASES[requestedFunctionAlias]];
//                          ^^^^ Element implicitly has an 'any' type

fn({ name: 'Michael!' });
//  ^^^^^^ Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'

我可以像这样解决其中的一些错误,

const FUNCTIONS_MATRIX = {
  [FUNCTION_ALIASES[FUNCTIONS_MAP.myFunction1 as keyof typeof FUNCTION_ALIASES]]: myFunction1,
  [FUNCTION_ALIASES[FUNCTIONS_MAP.myFunction2 as keyof typeof FUNCTION_ALIASES]]: myFunction2,
  [FUNCTION_ALIASES[FUNCTIONS_MAP.myFunction3 as keyof typeof FUNCTION_ALIASES]]: myFunction3,
};

const fn = FUNCTIONS_MATRIX[FUNCTION_ALIASES[requestedFunctionAlias as keyof typeof FUNCTION_ALIASES]];

但这看起来很乱,它仍然没有解决fn({ name: 'Michael!' });的错误。

我可以在这里做什么?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    首先声明FUNCTION_ALIASESFUNCTIONS_MAPas const。有了这个,你告诉打字稿他们的类型比key: string窄。

    const FUNCTION_ALIASES = {
      a1: "myFunction1",
      a2: "myFunction2",
      a3: "myFunction3",
    } as const;
    
    const FUNCTIONS_MAP = {
      myFunction1: "a1",
      myFunction2: "a2",
      myFunction3: "a3",
    } as const;
    

    然后从 requestedFunctionAlias 中删除类型声明 string,因为它丢失了类型信息 - 它的类型是文字 "a1" 并且打字稿需要它,以便在类型检查时准确知道将返回哪个函数:

    const requestedFunctionAlias = "a1";
    

    【讨论】:

    • 这不会解决 fn({ name: 'Michael!' }); 处的 TS 错误。此外,这里的requestedFunctionAlias 是字面上的a1,但实际上,它是一个传入的动态参数。我编辑了OP
    猜你喜欢
    • 2023-03-23
    • 2016-12-27
    • 2021-08-16
    • 2023-02-09
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    相关资源
    最近更新 更多