typescript 提取函数内的对象键

y4ekin9u  于 2023-03-19  发布在  TypeScript
关注(0)|答案(1)|浏览(139)

它经常比我们需要的类型是给定对象的键的并集。解决方案很简单:

const myObject = { 
  "key" : "value", 
  "anotherKey" : "anotherValue" 
}

type keysOfMyObject = keyof typeof myObject;

那么keysOfMyObject就是"key" | "anotherKey"
很好,但现在我们尝试提供myObject类型。

const myObject : Record<string,string> = { 
  "key" : "value", 
  "anotherKey" : "anotherValue" 
}

type keysOfMyObject = keyof typeof myObject;

ooops keysOfMyObject现在是string,在这种情况下,我们可以将myObject的类型限制为Record<'key' | 'anotherKey'>,但是如果对象是函数的参数,并且可能有任何字符串作为键呢?

const myFunction = function(dictionary : Record<string,string> ) {
  return function acceptOnlyKeysFromDictionaty(key : keyof typeof dictionary){
    console.log("key", key); 
  }
};

你知道如何使函数acceptOnlyKeysFromDictionary正确键入,使它只接受来自dictionary的键作为键吗?上面它接受任何字符串,所以myFunction({"allowedKey" : "value"})("illegalKey")仍然可以作为 typescript 。

e4yzc0pl

e4yzc0pl1#

解释@parzh .的回答

const myFunction = function <D extends Record<string, string>>(dictionary: D) {
  return function acceptOnlyKeysFromDictionaty(key: keyof typeof dictionary) {
    console.log("key", key);
  }
};

演示:https://www.typescriptlang.org/play?#code/FAYw9gdgzgLgBAWwJ4DECuEQwJaTgXjgDMMtcI4AeAETgFMAPGOiAEyjgCU7wAnVyrF7YIAcwA0cISNEA+WQApW2MpACGvJAC441AJRwA3sDhxedGGl4USmHHjUgQdAA4wA8hAA2SANJ0kKBReMARqFXsINRgkBQBrAJ0EpDAiOBiXOlS4ZVUozQNjU1NwaDAvOgA6LzBRBQAiZPrJZL0AbhM4AF9gLra4YFBIWDhHZzcCRFRSSIUiuHqYKHqdAHIRVkZV3r1BsdcYBqX63f23BoArZb0gA

相关问题