Question was already asked here but both the solutions provided don't address nor solve the issue
I was following some TypeScripts examples about generics, in the specific this one.
The example is pretty straightforward:
function pickObjectKeys<T, K extends keyof T>(obj: T, keys: K[]) {
let result = {} as Pick<T, K>
for (const key of keys) {
if (key in obj) {
result[key] = obj[key]
}
}
return result
}
const language = {
name: "TypeScript",
age: 8,
extensions: ['ts', 'tsx']
}
const ageAndExtensions = pickObjectKeys(language, ['age', 'extensions'])
This works. However, if passing the array as a variable, like so:
const keys = ['age', 'extensions']
...
pickObjectKeys(language, keys)
the TypeScript compiler gives error 2345:
Argument of type 'string[]' is not assignable to parameter of type '("age" | "extensions" | "name")[]'.
Type 'string' is not assignable to type '"age" | "extensions" | "name"'.
What's the catch? How to address this issue?
keysis inferred asstring[], not["age", "extensions"]or("age" | "extensions")[].const keys : ("age" | "extensions")[] = ["age", "extensions"]orconst keys = ["age" | "extensions"] as ("age" | "extensions")[]. Because if you just doconst keys = ["age", "extensions"]it's totally legal to dokeys.push("foobar")but that would cause an error inpickObjectKeys