Typescript here complains:
Implicit conversion of a ‘symbol’ to a ‘string’ will fail at runtime. Consider wrapping this expression in ‘String(…)’.
type TableProps<Row extends Record<string, unknown>, K extends keyof Row> = {
rows: Array<Row>,
ace: K,
}
const data: TableProps<any, string> = {
rows: [
{ name: 'Ram', age: 2 },
{ name: 'Toy', age: 12 },
],
ace: 'name',
}
const func = <Row extends object, K extends keyof Row>(rows: Row, ace: K) => {
return `hello-${ace}-ws`;
}
Here is the link to play with code.
How do i assure typescript that they key would always be a string?
2
Answers
You can modify the generics to constrain
K
bystring
and defineRow
as an object type that’s indexed byK
(likeRecord<K, unknown>
). Here’s an example:TS Playground
Your
data
property is generically typed to know that itsace
is going to be astring
, but yourfunc
is not. Depending on how broadly you want to change your definitions, you could fix the error message in a few ways. For example, you can just makefunc
know that its argument is a string:But since your
TableProps
‘sRow
type knows it usesstring
as itsRecord
‘s keys, you could remove theK
generic type entirely, replacing it withString
: