TypeScript function that differentiates types and provides extra information

Can a type guard function also provide additional data?

Like this example:

function isNumberData(value: any): [value is number, message: string] {
    if (typeof value === 'number') {
        return [true, ""]
    } else {
        return [false, `Incorrect typeof ${typeof value}`]
    }
}

Answer №1

When working with TypeScript, it is important to remember that type guards must return a boolean value and nothing else. Any additional information must be handled separately.

Similarly, assertion functions face the same restriction - they can only throw errors or return void.

If you need to extract extra details beyond narrowing the type, you will have to handle it in a different part of your code, like so:

const result = checkType(value);
if (!result) {
  const detail = getDetail(value);
  // ...
}

While it is possible to assign outer scope variables to capture the desired information, such patterns are not considered functional and may pose challenges when ensuring TypeScript compatibility.

let detail: string;
function checkType(value: any): value is number {
    if (typeof value === 'number') {
        return true
    } else {
        reason = `Incorrect type: ${typeof value}`;
        return false;
    }
}

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

Using FIND to search an array object results in an error: Type 'undefined' is not compatible with type ''

I'm currently attempting to search for an element within one array and then assign it to another array object. However, I keep receiving the following error message: Type 'ClosureSummary | undefined' is not assignable to type 'Closure ...

Is it possible for me to disable the eslint typedef rule for destructuring within lambdas?

Is it possible to disable the typedef rule only for array or object destructuring in lambdas? getPersonsNames(): string[] { type Person = { name: string; age: number }; const persons: Person[] = [ { name: `Jan Kowalski`, age: 12 }, ...

Angular 2 App Encountering Async Pipe Issue with Observable

I have successfully implemented pagination in my Angular 2 application, but I am encountering an issue related to the async pipe: Invalid argument '' for pipe 'AsyncPipe' Upon researching this error, it seems to be linked to the asy ...

How to best handle dispatching two async thunk actions in Redux Toolkit when using TypeScript?

A recent challenge arose when attempting to utilize two different versions of an API. The approach involved checking for a 404 error with version v2, and if found, falling back to version v1. The plan was to create separate async thunk actions for each ver ...

The TypeScript error message reads: "You cannot assign type 'undefined' to type 'ReactElement'."

I'm encountering an error in my react project TypeScript error Argument of type 'ReactNode' is not compatible with parameter of type 'ReactElement<any, string | JSXElementConstructor<any>> | ReactElement<any, string | JSX ...

Deleting items from a JavaScript object array in Angular using TypeScript can be achieved by using various methods and

Here is the structure of my object array: 0: {Name: "Albert", Id: 32} 1: {Name: "George", Id: 34} 2: {Name: "Jane", Id: 35} Although the request is successful, the array remains unchanged. However, upon refreshing the app, the item (student) is deleted. ...

Discovering the presently held variant type and assigning fresh variables of that same type

Within my code, I am working with a versatile boost::variant containing types like: typedef boost::variant< uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, float, double, std::string > StorageTt; At some point, a variable va ...

Is there a way to automatically close the previous accordion when scrolling to a new one on the page?

Currently, I am working with the material-ui accordion component and facing an issue where all accordions are initially opened. As I scroll down the page and reach a new accordion, I want the previous ones to automatically close. The problem arises when tr ...

What kind of impact does the question mark at the conclusion of a function title make?

I came across the following TypeScript code snippet: class Foo { start?(): void {} } What caught my attention was the ? at the end of start. It appears to be making the function optional (but how can a function be optional and when would you need tha ...

What could be causing this error when running nodemon in an Angular TS file?

One issue I am facing is that upon running the npm run dev command, I encounter the error message stating that 'node_modules is not recognized as an internal or external command'. Here is an image showing the specific error: https://i.sstatic.ne ...

jester: constantly jest navigator's mock & check against userAgent/vendor

Purpose: Need to iterate through different combinations of the userAgent Simulate navigator behavior Execute the test Observation: I simulated the navigator.userAgent, simulation works as planned, first test executes as expected Second simulation is per ...

Obtaining the class instance of a component through reference

I am facing a situation where I have a typescript class that extends React.Component: class CustomComponent extends React.Component<{}, {}> { constructor(props: {}) { super(props); } public render() { return < ...

Retrieve the querystring parameter in angular2 using this.activeRoute.queryParams._value

While debugging in chrome, I came across this object: this.activeRoute.queryParams._value The constructor passes activeRoute as private activeRoute: ActivatedRoute Interestingly, when I'm in vs code and type this.activeRoute.queryParams, ._valu ...

Struggling to retrieve an Object from an HTMLSelectElement within an Angular project

Can you help me with this code snippet: <select #categorySelect (change)="goToCategory.emit(categorySelect.value)" style="..."> <option selected hidden>All</option> <option [ngValue]="categ ...

What steps can I take to fix the 'node module error' while deploying a project on Vercel?

While working with the world-countries package, I encountered an issue during deployment in Vercel. The error message indicated that a ';' was missing in the index.d.ts file of world-countries located in the node_module directory. Here is the ex ...

Offer identical service instances using various tokens

I am faced with a situation where I have 2 distinct interfaces: export interface IUserService { ... } export interface IUserStorageService { ... } In order to consolidate functionalities from both interfaces, I have created a single service that ...

What is the best way to incorporate and utilize the JavaScript MediaWiki API in my projects?

I find it frustrating that the documentation for this library is lacking, making it difficult to figure out how to import it into my Typescript/React project. I am attempting to utilize the MediaWiki officially supported library but the examples provided ...

Is it possible to instruct TypeScript to add the ".js" extension to export/imports when using Node 16?

Is your TS 4.7 library configured to use ESM modules? Let's take a look at your tsconfig.json: "target": "ES2020", "module": ""ES2020", "lib": ["ES2020"], "moduleRe ...

What is the reason behind document.body not being recognized as an HTMLBodyElement?

Why does Visual Studio suggest that document.body is an HTMLElement instead of an HTMLBodyElement? I've searched for an answer without success. class Test { documentBody1: HTMLBodyElement; documentBody2: HTMLElement; cons ...

Encountered an error of 'npm ERR! invalid semver' when attempting to release an npm package

npm ERR! code EBADSEMVER npm ERR! invalid semver: npm ERR! Check out the full log of this run here: I attempted to reinstall node and semver, but unfortunately it did not resolve the issue. ...