【问题标题】:function argument should be type of one of the object's key type函数参数应该是对象的键类型之一
【发布时间】:2018-10-26 03:01:34
【问题描述】:

在打字稿中, 我有一个功能:-

   function updateSetting(settingName, settingValue: string[]| number | null) { 
      this.props.updateSetting({[settingName]}: settingValue)
  }

我也有一个对象,所以我有一个接口

   interface Setting {
      names: string[]
      city: string | null
      age: number
   }

所以,我想使用对象作为参数,并且我还希望将对象的一个​​属性作为参数传递,该参数在运行时决定。所以在我的函数 settingName 可以是“名称”或“城市”或“年龄”,所以我想从界面本身分配类型。

我不想写(settingValue: string[]| number | null)我想写类似的东西

settingValue: valueof Setting

因为设置值可以是names, city, age的任何类型。

我怎样才能在打字稿中实现这一点?

【问题讨论】:

标签: typescript


【解决方案1】:

如果您想动态设置 settingValue 的类型和界面,您可以尝试:

settingValue: Setting[keyof Setting]; // string[]| number | null

或者如果你想要设置它的键而不需要它们的类型:

settingValue = keyof Setting ; // names| city | age

【讨论】:

    【解决方案2】:

    除了settingValue 的类型之外,您还可以改进您的功能,您还可以确保settingNamesettingValue 是一致的:

    function updateSetting<TKey extends keyof Setting>(settingName: TKey, settingValue: Setting[TKey]) {
        //...
    }
    
    interface Setting {
        names: string[]
        city: string | null
        age: number
    }
    
    updateSetting("names", [""])
    updateSetting("age", [""]) //error
    

    我们使用keyof 运算符来指定泛型参数Tkey 必须是字符串文字类型,它是Setting 的键之一,然后我们指定settingValue 必须具有@ 的字段的任何类型987654329@ 对给定键使用类型查询Setting[TKey]

    如果您通常将它与常量键一起使用,这种方法可以确保更多的类型安全性。如果要传递任意字符串,则需要使用类型断言,settingValue 的类型将与 Setting[keyof Setting] 相同:

    let str;
    updateSetting(str as keyof Setting, 0) //ok
    updateSetting(str as keyof Setting, new Date()) //error
    

    【讨论】:

      猜你喜欢
      • 2019-12-09
      • 1970-01-01
      • 2015-01-31
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 2020-12-08
      • 2021-01-17
      相关资源
      最近更新 更多