I have an object containing multiple types of values:
interface Foo {
id: number;
data: FooData;
username: string;
notes: string;
}
const foo: Foo = {
...
}
I have a function that requires a string, and am iterating through a specific list of fields in my object to use in that function, all of which contain string values:
const renderString = (value: string) => {
...
}
const fooKeys: keyof Foo = ["username", "notes"];
fooKeys.map((key) => {
renderString(foo[key])
}
The issue is that foo[key]
can be a string
, number
, or FooData
object, so I want to specify that foo[key]
will ONLY be a field value of Foo
with a key matching one in fooKeys
, since they are all going to be string values.
We can assert foo[key] as string
but that doesn't protect us against bad keys in fooKeys.