I'm curious to know the purpose of 'as never' in this particular code snippet

I'm having trouble understanding the concept of 'as never' in this particular code snippet. I've come across the definition that it signifies something that never occurs or excludes other types, but I can't seem to grasp its usage in the context provided below.

import { View, Button, Text, StyleSheet, FlatList, TouchableOpacity, Image } from 'react-native'
import React from 'react'
import { useNavigation } from '@react-navigation/native'

const data = [
  {
    id: 1,
    title: 'Google Search',
    screen: 'MapScreen',
  },
  {
    id: 2,
    title: 'I\'m Feeling Lucky',
    screen: 'MapScreen',
  }
]

const NavOptions = (props: NavProps) => {
  const navigation = useNavigation();
  return (
    <FlatList
      data={data}
      keyExtractor={(item) => item.id}
      horizontal
      renderItem={({ item }) => (
        <View style={styles.container}>
          <TouchableOpacity
            onPress={() => props.term && navigation.navigate(item.screen as never, {
              term: props.term,
            } as never)}
            style={styles.button}>
            <Text style={styles.text}>{item.title}</Text>
          </TouchableOpacity>
        </View>
      )}
    />
  )
}

const styles = StyleSheet.create({
  container: {
    padding: 10,
  },
  button: {
    backgroundColor: "#f8f9fa",
    padding: 10,
  },
  text: {
    color: "black",
    textAlign: "center",
  },
});

type NavProps = {
  term: string;
}

export default NavOptions

Answer №1

The code is incorrect.

Your interpretation of the never type is mostly accurate: it is a type that has no valid values and is often the result of intersecting incompatible types; it signifies code that cannot be reached, scenarios that are logically impossible, and expressions that cannot be fully evaluated. An example of this is functions that throw exceptions instead of returning normally:

function raiseRangeErr(e: string): never {
    throw new RangeError(e);
}

function div(a: number, b: number): number {
    return b !== 0 ? a / b : raiseRangeErr("division by zero");
}

never stands out because expressions of this type can be assigned to any other type. This is possible because, since never has no valid values, it will not fail to be a member of the target type.

The intention behind using never in the code snippet was likely to suppress errors related to unassignable types. However, from a type theory perspective, this is incorrect: code featuring never should be unreachable, which is not the case here.

It is generally recommended to avoid type assertions. If you can eliminate these assertions without encountering errors, it's best to do so. If a type assertion is necessary, opt for a type specific to the situation or, in extreme cases, use as any. The only scenario where as never might be somewhat acceptable is when calling a function that you know never returns, but you lack appropriate type definitions to reflect that. For instance:

function raiseRangeErr(e: string): unknown {
    throw new RangeError(e);
}

function div(a: number, b: number): number {
    return b !== 0 ? a / b : raiseRangeErr("division by zero") as never;
}

Ideally, updating your type definitions would be a better solution in such cases.

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

Error message: The types in React Redux typescript are incompatible and cannot be assigned to each other

I recently converted my React App to TypeScript and encountered an error that I'm having trouble understanding. Any help would be greatly appreciated. Here is the code for my "mapStateToProps" function: function mapStateToProps(state: AppState): MapS ...

Comparison between typings and @types in the NPM scope

There are different approaches when it comes to handling TypeScript definitions. In some cases, the typings tool is used, as seen in projects like angular/angular2-seed. Alternatively, some projects use scoped NPM packages with the prefix @types, complete ...

Having issues with NGXS subscription not functioning properly when selecting a variable

Currently, I am working with Angular 11 and NGXS. One issue I am facing involves a subscription for a variable in the state. Here is the problematic subscription: @Select(state => state.alert.alerts) alerts$: Observable<any[]> ngOnInit(): void { t ...

When the React Native Expo app is running, the TextInput form is covered by the keyboard

When I launch the app using expo and implement my DateFormInput component, the issue of Keyboard covering TextInput arises. Despite trying packages like "@pietile-native-kit/keyboard-aware-scrollview", "@types/react-native-keyboard-spacer", "react-native-k ...

Creating rectangular shapes on the canvas with the help of react hooks

I have a React+Typescript web application and I am currently working on implementing the functionality to draw rectangles on a canvas. My goal is to utilize React hooks instead of classes in order to achieve this. The desired outcome is to enable the user ...

Is it possible to measure the CPU utilization in a TypeScript application programmatically?

Is there a method to calculate CPU usage as a percentage and record it in a file every 20 milliseconds? I'm interested in exploring different approaches for accomplishing this task. Your insights would be greatly appreciated! I've come across so ...

Creating Production Files for Web using RxJs and TypeScript

I am interested in developing a JavaScript Library using RxJs (5.0.0-Beta.6) and TypeScript (1.8.10). My TypeScript file is successfully compiling. Below are the files I have: MyLib.ts: /// <reference path="../../typings/globals/es6-shim/index.d.ts" ...

Generating a custom type in Typescript based on specific array keys

Imagine I have a structure like this: export interface MyObject { id: number title: string } and then I create an array as shown below: const myArray: MyObject[] = [ { id: 2358, title: 'Item 1' }, { id: 85373, title: &a ...

What is the importance of always catching errors in a Promise?

In my project, I have implemented the @typescript-eslint/no-floating-promises rule. This rule highlights code like this - functionReturningPromise() .then(retVal => doSomething(retVal)); The rule suggests adding a catch block for the Promise. While ...

Utilizing Typescript's baseUrl compiler configuration for node development

Is there a way for node's module loader to support TS's baseUrl compiler option? With the introduction of the baseUrl compiler option in TS 2, project relative require() and import requests are now possible. However, this feature requires that ...

What does `(keyof FormValues & string) | string` serve as a purpose for?

Hey there! I'm new to TypeScript and I'm a bit confused about the purpose of (keyof FormValues & string) | string. Can someone please explain it to me? export type FieldValues = Record<string, any>; export type FieldName<FormValues ...

Oops! Looks like there's a type error in module "*.mdx" - it seems that it doesn't have the exported member "metadata". Maybe try using "import metadata from "*.mdx"" instead?

I am attempting to extract metadata from an mdx file. I have followed the guidelines outlined in NextJS Markdown Frontmatter, but encountered build errors. It is important to note that I am unable to utilize fs. Code Section Page.tsx File import Conte ...

Creating React Components with TypeScript: Ensuring Typechecking in Class and Function Components

Want to ensure typechecking works when defining React Class/Function components in TypeScript? Struggling to find a comprehensive guide on how to do it correctly. I've managed to define the Props and State interfaces, but I'm unsure about how to ...

Validating multiple conditions in Typescript by passing them as function parameters

As a beginner in TS/JS, I am looking to validate multiple conditions passed as arguments to a function. For instance, currently I am verifying the user role name, but in the future, I may need to check other conditions. validateUserDetails(): Promise< ...

Unveiling the seamless integration of TypeScript with webpack/metro mainFiles module resolution

Scenario Setup In Webpack, the mainFiles module resolution feature allows for resolving specific files based on the environment. This concept is exemplified by: | Button | | - index.ts | | - index.performer.ts | | - index.customer.ts // page.ts im ...

The field 'shouldComponentUpdate' cannot be reassigned to itself

I encountered a TypeScript error while using shouldComponentUpdate: The error message states: "Property 'shouldComponentUpdate' in type 'Hello' is not assignable to the same property in base type Component<IProps, any, any>." ...

Getting the hang of using and translating typescript .tsx files with jsx in React-native

Recently, I have ventured into the world of React-native after having experience with reactjs+typescript. Wanting to test its capabilities, I decided to set up a simple project. My tool of choice for development is VS Code. After following a basic tutoria ...

What is the process for incorporating TypeScript types into a JavaScript library?

After adding p5 and @types/p5 to my project, I imported p5 in the following way: import * as p5 from 'p5' However, when I tried using p5.createImage(100, 100), I encountered this error message indicating that 'createImage' is not a re ...

Angular 2, the change event is not triggering when a bootstrap checkbox is clicked

Encountering an issue, the (change) function is not triggering in a specific checkbox. <input [(ngModel)]="driver.glasses" name="glasses" type="checkbox" class="make-switch" (change)="changeFunction()" data-on-color="primary" data-off-color="info"&g ...

Transforming encoded information into a text format and then reversing the process

I am facing an issue with storing encrypted data in a string format. I have tried using the TextEncoder method but it seems to be creating strings with different bytes compared to the original ArrayBuffer. Here is the line causing the problem: const str ...