Let's say the following object is created using the specified type definition. It must use the index signature [key: string] as the object is allowed to have any keys, or even no key at all.
interface CreateObject {
[key: string]: {
foo: string
bar: number
}
}
const myObject: CreateObject = {
fooKey: {
foo: "something",
bar: 1
},
barKey: {
foo: "something else",
bar: 2
}
}
Now, let's say I want to create a function that takes in a key parameter. The value of key should be equal to an actual key value within myObject, i.e. in the example above key should only ever be equal to fooKey or barKey.
interface SomeFunction {
(key: keyof typeof myObject): void
}
const someFunction: SomeFunction = (key) => {
console.log(myObject[key].foo)
}
This won't work as keyof typeof myObject is equal [key: string], therefore as long as key in someFunction(key) is equal to any string then it won't have any type errors.
How do I ensure that only the actual keys within myObject can be passed in as the key parameter? For example:
someFunction("fooKey") // should pass
someFunction("barKey") // should pass
someFunction("notAValidKey"); // should fail
Here's a Playground link demonstrating the issue.