Typescript Property 'toString' does not exist on type

Viewed 337

This one was a bit confusing to me. In my search function I'm looking for substring matches of the search keywords and so before any comparison of an object I just convert all of the properties to a string and then check for substrings.

To the best of my knowledge, everything in javascript has a .toString method and so even when type ambiguity is in play there shouldn't be any issue in calling the method.

For some more context, here is the code:

const results = rows.filter((row) =>
  fields.some((field) =>
    row[field].toString().toLowerCase().includes(search)
  )
);

The rows variable is of type ListFields[L] where L is a generic that extends keyof ListFields. The fields variable is an array of type keyof ListFields[L] so there shouldn't be any conflict with trying to access properties that don't exist.

The definition for ListFields is below:

type ListFields = {
  Users: MetaData &
    LocationData & {
      wuNumber: string;
      dispName: string;
      firstName: string;
      lastName: string;
    };
  // ... Other similar list definition
}

// MetaData and LocationData if necessary:
type MetaData = {
  Title: string | null;
  FileSystemObjectType: number;
  Id: number;
  ServerRedirectedEmbedUri: null | string;
  ServerRedirectedEmbedUrl: string;
  ID: number;
  ContentTypeId: string;
  Modified: string;
  Created: string;
  AuthorId: number;
  EditorId: number;
  OData__UIVersionString: string;
  Attachments: boolean;
  GUID: string;
  ComplianceAssetId: null | number;
};

type LocationData = {
  Address: string;
  CountryOrRegion: string;
  State: string;
  City: string;
  PostalCode: string;
  Street: string;
  GeoLoc: string;
};
1 Answers

While string, boolean, and number have a toString function, null does not. You can either use JSON.stringify or exclude the properties with null as a possibility.

Related