【问题标题】:Writing a function that picks values from an object and return the correct types编写一个从对象中选择值并返回正确类型的函数
【发布时间】:2021-03-26 21:30:49
【问题描述】:

我有一个函数可以根据你给它的字符串提取一个值。当我执行函数时,如何使函数的输出键入它已提取的值。

const config = {
  one: 'one-string',
  two: 'two-string',
  three: true,
  four: {
    five: 'five-string',
    six: false
  },
  seven: [
    'eight', 'nine', 'ten'
  ]
}

type Config = {
  one: string;
  two: string;
  three: boolean;
  four: {
    five: string;
    six: boolean;
  }
  seven: string[]
}

type GetConfig = (key: keyof Config) => Config[keyof Config];

export const getConfig: GetConfig = key => {
  return config[key];
};

getConfig('seven').map(...);

目前我收到以下错误:

类型'string | 上不存在属性'map'布尔值 |字符串[] | { 五:字符串;六:布尔值; }'。属性“地图”不存在 输入“字符串”。

因为getConfig 没有像上面指出的那样被键入为数组,而只是被键入为任何一种可能的类型。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    如果您将GetConfig 类型设为泛型,getConfig 将被正确键入:

    type GetConfig = <K extends keyof Config>(key: K) => Config[K];
    

    或者,您可以直接在常量上指定泛型类型,因此您不必显式指定返回类型:

    const getConfigAlt = <K extends keyof Config>(key: K) => config[key];
    

    TypeScript playground

    【讨论】:

    • 谢谢!这正是我想要达到的目标。
    【解决方案2】:

    你可以这样做,可以在打字稿游乐场尝试一下

        const config = {
        one: 'one-string',
        two: 'two-string',
        three: true,
        four: {
            five: 'five-string',
            six: false
        },
        seven: ['eight', 'nine', 'ten']
    }
    
    type Config = {
        one: string;
        two: string;
        three: boolean;
        four: {
            five: string;
            six: boolean;
        }
        seven: string[];
    }
    
    type GetConfig = (key: keyof Config) => Config[keyof Config];
    
    const getConfig: GetConfig = key => {
      return config[key];
    };
    
    const val = getConfig('seven').valueOf() as [];
    val.map(m => {
        console.log(m);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      相关资源
      最近更新 更多