TypeScript error: Type 'string' is not assignable to union value

Hello friends.

I've picked up my side project again this week and I'm trying to add a new feature (required field indicator). It's a component library for forms. It's expecting specific form data:

export interface Form {
  databaseId: number
  ... extra stuff ...
  customRequiredIndicator?: string | null
  requiredIndicator?: "TEXT" | "ASTERISK" | "CUSTOM" | null
  submitButton: Button
  formFields: { nodes: Field[] }
}


When a user passes in the form data, they may or may not include the
requiredIndicator
. If they do, it can be either "TEXT", "ASTERISK", "CUSTOM" or a null value.

I thought I could tell TypeScript that these are the only 3 string values that it could be and have it work. But when I actually test it out, I get the following error:

Type 'string' is not assignable to type '"TEXT" | "ASTERISK" | "CUSTOM" | null | undefined'.


I've tried a bunch of things and can't seem to sort it out. I think the issue is that because I have no control over the data that the user is passing into the <Form> component, I can't use a type assertion.

I'm thinking that just typing it as 'string' is fine enough. I just thought that TypeScript could do this too.

I could stand to learn more, so I'm open to anything y'all have for me.

Thanks!
Solution
Typescript infers the types from the json to be plain types like string, and so you can assert type for it to be proper. To do so you can do the following, where Form is the type you defined

import data from "../data/query.json"
const mockData = data as Form
Was this page helpful?