Ensure proper type checking for reducer using Flow

Trying to incorporate Flow into a Redux codebase has been my current challenge. As someone new to Flow, I have some experience with TypeScript.

My goal is to detect incorrect action types within the reducer function.

type Action = 
  | { type: 'sample' }
  | { type: 'django' }  
  ;

type State = {
  content: string,
};

const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    // OK
    case 'sample':
      return { content: '' };

    // Should raise a type error, because the action type 
    // will never be equal to "error" 
    case 'error':
      return { content: '' };

    default:
      return { content: '' };
  }
};

Try it in the Flow Playground
Try it in TypeScript Playground

I am puzzled as to why Flow fails to catch the error in this particular scenario. Even though I explicitly set the type to be 'sample' or 'django', Flow still infers the type property as a string.

Can anyone point out what I might be missing?

Thanks!

Answer №1

This issue appears to be a potential bug within the flow system, but there is a workaround available that enforces strict verification:

type TaskType = 'task1' | 'task2'
type Task = {type: TaskType}

type Status = {
  message: string
}

const updateStatus = (status: Status, task: Task): Status => {
  const taskType: TaskType = task.type;
  switch (taskType) {
    // This block should trigger a type error since "error" 
    // is not included in the TaskType enum
    case 'error':
      return { message: '' };
    default:
      return status;
  }
};

Upon running this code snippet, you will receive the following output:

13:     case 'error':
             ^ string literal `error`. This type is incompatible with
9:   const taskType:TaskType = task.type;
                ^ string enum

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Typescript, the error message "Property 'content' is not found on the type 'HTMLElement'" indicates that the 'content' property is not

Whenever I attempt to access the content of a meta tag, I encounter an error: document.getElementById('mymetatag').content While this code works in Javascript, TypeScript throws an error that says: Property 'content' does not exist o ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

The 'string' data type cannot be assigned

Let me share how I define and utilize my font sizes in my custom React app: FontSizes.ts const fontSizes = { xs: 'xs', sm: 'sm', base: 'base', lg: 'lg', xl: 'xl' ...

Is it possible to enhance an external class with a non-static method using prototypes?

Is it possible to use prototypes to add a function for a class instance? allowing me to access this or __proto__ keyword inside my method, like so: class PersonClass { name: string; constructor(name: string) { this.name = name; } sayHello() ...

What steps should be followed to properly validate an unsubmitted form in Angular?

To ensure that the user submits the form before navigating to another page, I want to implement a feature where an error dialog pops up if the user types in the form but hasn't submitted it yet and tries to click a link to go to a different page. How ...

Issue with Typescript npm script including compilation and nodemon issue

After exploring various SO links, I tried to find a way to simultaneously run both tsc -w and nodemon app.js using a single command. The link I referred to is: How do I execute typescript watch and running server at the same time? Working on a node.js pr ...

Tips for defining a dynamic class variable in React with Flow

I am working with a map that assigns a reference to items, specifically in this scenario it is a video. const ref = this[`video-${index}-ref`]; I am seeking guidance on how to properly type this using Flow. The number of indexes may vary. ...

"Encountering a glitch in the Typescript/Node API where Express routes

Encountering a peculiar issue here - when attempting to import my router from an external file and add it as a route, I keep getting this unusual error where the string appears to be enclosed in double quotes. https://i.sstatic.net/nm9Wn.png ...

Typescript threw an error: Zod was anticipating a string, but instead it got

I am encountering a Zod error multiple times while attempting to submit my req.body data to the Prisma ORM using Insomnia: ZodError: [ { "code": "invalid_type", "expected": "string", "received" ...

I am having trouble viewing the input value on my Angular5 form

Here is the HTML code snippet that I've written: <input type="text" name="fechainscripcion" #fechainscripcion="ngModel" [(ngModel)]="alumno.fechainscripcion" value="{{today | date:'dd/MM/yyyy'}}" class="form-control" /> This is a seg ...

What is the best way to change an array element into a string in TypeScript?

Within my Angular 2 component, I am utilizing an array named fieldlist which is populated by data retrieved from an http.get request. The array is declared as follows: fieldlist: string[] = []; I populate this array by iterating through the JSON response ...

Performing a series of Http Get requests in Angular 2 with an array that can

Seeking assistance with an Observable http sequence that involves making two dependent http calls to an api. The first call returns an Array of Urls, and the second call makes get requests for each url in the array and then returns the responses on the str ...

Bring Jest into everyday script

Can Jest be imported into a file that is not intended to run as a test and does not include any test cases (such as a support module for tests)? ...

Having trouble linking the date object with the default value of the date input field

Exploring how to set the default value of a date type input using property binding. Initially, I attempted to create a new date object in app.component.ts and then bind the [value] attribute of the date input to the currentDate property within app.compone ...

TS2305 error: The module "/node_modules/rxjs/Rx" does not contain the 'Subscribable' member to export

I am currently working on an Angular 5 project and here is the package.json file: { "name": "ff-client", "version": "0.2.0", "license": "", ... } After installing npm and angular-cli, I ran npm install to get the required modules. However, when I ...

Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing t ...

How can I set up a KeyboardEvent listener in JavaScript?

My attempt to use @keydown resulted in an error: Type 'Event | KeyboardEvent' is not assignable to type 'KeyboardEvent'. Type 'Event' is missing the following properties from type 'KeyboardEvent': altKey, c ...

Ensuring the safety of generic types in Typescript

Typescript is known for its structured typing, which is a result of the dynamic nature of Javascript. This means that features like generics are not the same as in other languages with nominal type systems. So, how can we enforce type safety with generics, ...

Exploring the use of the React hook "useMemo" with an array as a dependency

Recently, I started using react with typeScript and came across a problem while using the useMemo hook. Below is the code snippet from my fetching service: export default class FetchingService { datas: Data[] = []; constructor() { this.f ...

What steps do I need to take to export my TypeScript declarations to an NPM package?

I have multiple repositories that share similar functionality. I want to export type declarations to an NPM package so I can easily install and use them in my projects. Within the root directory, there is a folder called /declarations, containing several ...