【问题标题】:Typescript function accepting generic parameter and array of strings接受通用参数和字符串数组的打字稿函数
【发布时间】:2021-08-03 18:37:22
【问题描述】:

我正在创建一个泛型函数来检查泛型对象是否具有由字符串数组给出的属性。具体来说:

const staticStrings = ['name', 'age', 'address', 'photoUrl'...];
const genObject = {name: 'John Doe', bar: 'Biz'...}

不是所有的 foo 字符串都是 bar 的键,bar 可以有比 foo 更多的键。 通常在 JS 中我会实现这样的东西:

// This will render a component with value of genObject[ss] or null
 const renderStaticStrings = (staticStrings) => (genObject) => {
    return staticStrings.map((ss) => {
      return genObject.hasOwnProperty(ss) ? (
        genObject[ss]
      ) : null;
    });
  };

使用 Typescript,我在说对象应该是通用对象时遇到了一些麻烦,并且 字符串数组(staticStrings)可以包含对象的键。我尝试过的:

  const renderStaticStrings = <T extends Object, K extends keyof T>(staticStrings: K[]) => (genObject: T) => {
    return staticStrings.map((ss) => {
      return genObject.hasOwnProperty(ss) ? genObject[ss] : null;
    });
  };

实现:

renderStaticStrings(staticStrings)(completeProfile?.profile)}

错误:'string[]' 类型的参数不能分配给'(keyof Object)[]' 类型的参数。 类型“字符串”不可分配给类型“keyof Object”

有什么想法吗? 谢谢

【问题讨论】:

    标签: javascript typescript typescript-typings typescript-generics


    【解决方案1】:

    我认为这里没有必要使用泛型。试试这个:

    const renderStaticStrings = (staticStrings: string[]) => (genObject: Record<string, any>) => {
        return staticStrings.map((ss) => {
          return genObject.hasOwnProperty(ss) ? genObject[ss] : null;
        });
      };
    
    const staticStrings = ['name', 'age', 'address', 'photoUrl'];
    const genObject = {name: 'John Doe', bar: 'Biz'}
    
    renderStaticStrings(staticStrings)(genObject);
    

    【讨论】:

    • 是的,这行得通,我尝试过相同的解决方案,但我虽然有任何想法,但在这种情况下可能会很有用
    • any 如果您没有可以使用的较窄类型,则完全可以接受。如果您知道genObject 的值将是string,您可以使用它。如果此类型不同(有时是 string,有时是 number 等),那么您可以在该类型上创建一个泛型。
    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多