Cannot be assigned to type "never" after applying a type predicate

I'm attempting to merge a method for creating strongly typed strings with type predicates but encountering issues, as evidenced by the following code snippet: https://i.sstatic.net/2b9pO.png

The issue I'm facing is

TS2339: Property 'substr' does not exist on type 'never'
, which should have been rectified by the factory function:

export function isShortDateTimeWithSpaceDelimiter(
  datetime: string | ShortDateTimeWithSpaceDelimiter
): datetime is ShortDateTimeWithSpaceDelimiter {
  return DateTime.fromFormat(datetime, FORMAT_ISO_DATE_SPACE_DATE_TIME).isValid;
}

export function toShortDateTimeWithSpaceDelimiter(
  datetime: string
): ShortDateTimeWithSpaceDelimiter {
  if (isShortDateTimeWithSpaceDelimiter(datetime)) return datetime;
  throw new TypeError("Not a ShortDateTimeWithSpaceDelimiter");
}

It seems that TS is assuming the return type from the factory function is never, indicating that something is not functioning as intended ... What am I overlooking?

The type definitions are as follows:

// https://spin.atomicobject.com/2017/06/19/strongly-typed-date-string-typescript/
enum LocalDateTimeWithSpaceDelimiterBrand {}

/** Minute granularity: "yyyy-MM-dd hh:mm" */
export type ShortDateTimeWithSpaceDelimiter = string & LocalDateTimeWithSpaceDelimiterBrand;

Answer №1

This approach lacks practical use since it never really gets used. Instead of defining a new type with nominal typing like

(string & { __ShortDateTimeWithSpaceDelimiter__: unknown })
, maybe just using a regular intersection with a branding property would be more effective. Even then, do we really need nominal typing in this case? It seems like unnecessary overhead for minimal benefit 🤔

The so-called ShortDateTimeWithSpaceDelimiter type is basically just another way of saying never, making it quite pointless and unhelpful when it comes to defining a distinct kind of string.

If you're interested, there's an example of nominal typing in action in this TypeScript playground: playground

Instead of complicating things with

string & { __brand: "ShortDateTimeWithSpaceDelimiter" }
, it might be better to stick with a straightforward string. Why add unnecessary complexity? Defining types as if they were code itself can lead to over-engineering. Types should guide the design and implementation, not dictate it.

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

Issue TS2365: The operation of addition cannot be performed between an array of numbers and the value -1000

I'm encountering an error in my ng serve logs despite the function functioning properly with no issues. However, I am concerned as this may pose a problem when building for production. How can I resolve this error? uuidv4() { return ([1e7]+-1e3+- ...

Angular EventEmitter coupled with Callbacks

In order to create a custom button component for my angular application and implement a method for click functionality, I have the following code snippet: export class MyButtonComponent { @Input() active: boolean = false; @Output() btnClick: EventEmit ...

Issue encountered with express-jwt and express-graphql: TypeScript error TS2339 - The 'user' property is not found on the 'Request' type

Implementing express-jwt and graphql together in typescript has been a challenge for me. import * as express from 'express' import * as expressGraphql from 'express-graphql' import * as expressJwt from 'express-jwt' import s ...

Are you ready to put Jest to the test by checking the completion event of

The RxJS library's Observer triggers three main events: complete error next If we want to verify the occurrence of the complete event using Jest, how can this be achieved? For instance, we are able to test the next and error events by checking for ...

disappearing of vue event on single file component HTML element

I'm currently working on an ElectronJs project with Electron Forge, using the Webpack + Typescript template project In addition to that, I've integrated Vue and vue-loader for webpack in order to utilize Single File Component (SFC) files: { ...

You cannot call the 'datetime.date' object twice within the same variable assignment

Having some trouble with the code provided below. lastMonthEnd.strftime("%d") , lastMonthEnd.strftime("%b") and lastMonthEnd.strftime("%Y") is causing issues when used twice within a variable. Time variables are declared as ...

Exploring the concept of nested arrays in Angular 2 using Typescript

I'm exploring the possibility of defining an array in Angular 2 that contains multiple other arrays within it. To clarify, here's what I had initially: export class PaymentDetails { account: any[]; bpNumber: number; } The issue with t ...

Tips for showing JSON information in Nativescript

How can I display all values in a page using the provided JSON data? res { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "sensors": [ { "serial": "sensor1", "id": "1" }, ...

Tips for creating a redirect to a specific page after clicking a link in an email using Angular

I've been working on implementing a feature in Angular where users can click on a link provided in an email and then get redirected to the respective page after authentication. I've tried a few different approaches, but none of them seem to be wo ...

Determine the route parameter name based on the path string, for example, '/posts/:id'

My Route interface has a params object, and I'm looking to ensure type safety on that params object. For example: If we have a route config like this: { post: { path: 'posts/:id', } } navigate({ name: 'post', params: { wr ...

Tips for aligning the types of objects transmitted from a Web API backend to a React/Redux frontend

After creating a backend for my app using .net, I now have CRUD operations available to me. When performing a POST action, the response includes an entire new item object: {"Id":"7575c661-a40b-4161-b535-bd332edccc71","Text":"as","CreatedAt":"2018-09-13T15 ...

Steps to convert a variable's value into a datetime object

I am working on an input field in tkinter where the user enters a date in the dd/mm/yyyy format. I want to create two variables, one containing the three-letter abbreviation of the month and the other containing the year. The variable for the input date i ...

Challenges Faced with Implementing Active Reports in Angular 9

After following all the necessary steps outlined in this website to integrate Active Reports with Angular 9 (), I encountered an error when trying to compile my app: ERROR in The target entry-point "@grapecity/activereports-angular" has missing dependen ...

What does Typescript compile when aiming for ES5 / ES3?

I'm currently grappling with the nuances of when the Typescript compiler decides to transpile code in order to align it with my designated target ECMAScript version (ES5 or ES3). As an example, TSC has no problem transpiling for(var int of intArray); ...

Encountering issues with Angular2 App when attempting to load simulated data using a Promise causes malfunction

Looking to implement my mocked data loading using a promise, similar to the approach shown in the Angular2 Tutorial found here. Service (Mock): import { Injectable } from '@angular/core'; import { ERGEBNISSE } from "./mock-ergebnisse"; @Inject ...

What is the reason for a type narrowing check on a class property failing when it is assigned to an aliased variable?

Is there a way to restrict the type of property of a class in an aliased conditional expression? Short: I am trying to perform a type narrowing check within a class method, like this._end === null && this._head === null, but I need to assign the r ...

What is the best way to document a collection of generic interfaces while ensuring that they adhere to specific

I am currently utilizing a parser toolkit called Chevrotain to develop a query language that offers users the ability to enhance its functionality. Despite having all the necessary components in place, I am facing challenges when it comes to defining types ...

Assigning different data types with matching keys - "Cannot assign type '...' to type 'never'."

I have a question regarding my application, where I am utilizing values that can either be static or functions returning those values. For TypeScript, I have defined the static values along with their types in the following manner: type Static = { key1: ...

Hold off on utilizing information from a single observable until a later time

In my Angular component, I am working with the following code: @Component({...}) export class ComponentOne implements OnDestroy, OnChanges { readonly myBehaviourSub = new BehaviorSubject<Observable<MY_CUSTOM_INTERFACE>>(NEVER); constructo ...

JavaScript and TypeScript: Best practice for maintaining an Error's origin

Coming from a Java developer background, I am relatively new to JavaScript/TypeScript. Is there a standard approach for handling and preserving the cause of an Error in JavaScript/TypeScript? I aim to obtain a comprehensive stack trace when wrapping an E ...