skip to Main Content

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


  1. You can modify the generics to constrain K by string and define Row as an object type that’s indexed by K (like Record<K, unknown>). Here’s an example:

    TS Playground

    type TableProps<
      K extends string,
      Row extends Record<K, unknown> = Record<K, unknown>,
    > = {
      rows: Array<Row>;
      ace: K;
    };
    
    const data = {
      rows: [
        { name: "Ram", age: 2 },
        { name: "Toy", age: 12 },
      ],
      ace: "name",
    } satisfies TableProps<string>;
    
    const func = <K extends string, Row extends Record<K, unknown>>(
      rows: Row,
      ace: K,
    ) => {
      return `hello-${ace}-ws`;
    };
    
    
    Login or Signup to reply.
  2. Your data property is generically typed to know that its ace is going to be a string, but your func 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 make func know that its argument is a string:

    const func = <Row extends object>(rows: Row, ace: string) => {
      return `hello-${ace}-ws`;
    }
    func(data.rows, data.ace);
    

    But since your TableProps‘s Row type knows it uses string as its Record‘s keys, you could remove the K generic type entirely, replacing it with String:

    type TableProps<Row extends Record<string, unknown>> = {
      rows: Array<Row>,
      ace: string,
    }
    const func2 = (data: TableProps<any>) => {
      return `hello-${data.ace}-ws`;
    }
    func2(data);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search