Do you find it acceptable that this code passes type-checking?
function endlessLoop(): never {
while (true) {
}
}
let y = endlessLoop();
Why does y
exist and fall under the never
type category?
Do you find it acceptable that this code passes type-checking?
function endlessLoop(): never {
while (true) {
}
}
let y = endlessLoop();
Why does y
exist and fall under the never
type category?
never
is a specific type that can be assigned to any variable in TypeScript. When you declare let x = infiniteLoop()
, TypeScript automatically determines that the variable x
has the type never
, which is perfectly valid.
However, the usefulness of this lies in the fact that it prevents you from using the variable x
later on in your code, thereby avoiding potential semantic errors.
To explore more examples and explanations regarding the never
type in TypeScript, check out this resource.
It's important to note that TypeScript cannot statically detect infinite loops due to the undecidability of such problems in type systems.
By explicitly indicating the never
type, TypeScript enables developers to highlight and prevent unintended behaviors related to computations that are declared to never end.
In attempting to address my own query, it appears that the concept of never
in TypeScript is akin to a "bottom" type. However, "bottom" is considered a sub-type of all other types:
function f() : never
{
return (1 as never); // although this doesn't hold true for "as void".
}
Bottom serves as a member of every type (though with certain restrictions related to unboxed kinds), making it usable wherever a value of that type would be found (source).
Therefore, the function infiniteLoop()
has the ability to yield never
, which can exist as a subtype within any other type and even be explicitly declared like so:
let x:never;
Due to its nature as a sub-type of all types, variables can be "casted" (using as
) to the never
. Nonetheless, it is not permissible to assign a super-set to its corresponding sub-set; for instance, assigning the type Triangle
to never
results in an error, as demonstrated below:
type Shape = Square | Rectangle | Circle | Triangle;
function assertNever(x: never): never {
throw new Error("Unexpected object: " + x);
}
function area(s: Shape) {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.height * s.width;
case "circle": return Math.PI * s.radius ** 2;
default: return assertNever(s); // error occurs if cases are missing
}
}
I'm currently working on an application that utilizes the following technologies. In my Typescript file named "test.page.ts", there is a variable called "response: any" that I need to reuse in another Typescript file named "test2.page.html" by calling ...
Currently, I am in the process of updating an old Angular platform to a newer version. One requirement is that everything must have its type declaration. I encountered a problem with the label callback showing this error: The error message reads: "Type &a ...
I am unsure if the term sub interface is correct, but my goal is to develop an interface that inherits all properties from the super interface except for some optional ones. Despite referring to the TypeScript documentation for interfaces, I was unable to ...
I'm attempting to create a Yup validation schema for an object with the following structure: interface myObject { prop0: Date prop1: { nestedProp1: string nestedProp2: number [key: string]: string | number } } This is what I have tr ...
Within my Reducer file: case PumpActionTypes.EnterLocalMode: return commandOne.upsertOne( {id: action.payload.id, changes: { local: false }}, state ); When testing, I aim to verify that the local property is indeed modified to false. My curr ...
In my Typescript class, there is a map that I'm trying to initialize: public map:Map<string,string>; constructor() { let jsonString = { "peureo" : "dsdlsdksd" }; this.map = jsonString; } The issue I'm encounte ...
I need to make adjustments to an Angular application so that it can run smoothly on older machines. Is there a more efficient method for updating a text input field without using (keyup) to update after each keystroke? I haven't been able to find any ...
JSON [ { position: 1, name: 'test', value: 1.0079, symbol: 'HHH' }, { position: 2, name: 'test2', value: 4.0026, symbol: 'BBB' }, { position: 3, name: 'test3', value: 6.941, symbol: 'BB' }, ...
I'm currently diving into Type Relations in TypeScript. Can someone help explain what happens when we intersect the types represented by these two expressions: {a:number}[] & {b:string}[] Does this result in {a:number, b:string}[] ? Any clarificat ...
Utilizing es6-promise with TypeScript version 2.1.1 that targets ES5 and webpack in my project has presented some challenges. app.ts import "es6-promise/auto"; export class Foo { bar() : Promise<string>{ return Promise.resolve("baz"); ...
Currently, I am attempting to navigate outside of my application. I have experimented with using window.location.href, window.location.replace, among others. However, when I do so, it only appends the href to my domain "localhost:4200/". Is it possible th ...
When we call the baz function with the code provided, the typeahead will display 'a' and 'b' as potential values. https://i.stack.imgur.com/SrKo7.png If additional documentation is needed for each of these values, how can it be accomp ...
After working on my Angular project and closing the IDE last night, I encountered an odd problem today. The project doesn't seem to recognize certain libraries such as Int8Array, Int16Array, Int32Array... And many others. While the project is still ab ...
**Everything is working fine except for one error in the console. How can I remove this error? Can anyone please help me? Save, Edit, and searching are working perfectly fine. ** public campaignCategoryFormGroup$: FormGroup = this.fb.group({ // 'c ...
Consider the structure of an array : [ branch_a: { holidays: [] }, branch_b: { holidays: [] }, ] In this structure, branch_a, branch_b, and ... represent dynamic keys. How can this be properly declared in typescript? Here is an attempt: ty ...
We encountered a compiling error after upgrading from TypeScript 4.7.4 to a newer version (specifically, 4.8.4). This error was not present in our codebase when using 4.7.4. To pinpoint the issue, I have extracted the error into a small code snippet. When ...
Exploring TypeScript's compiler API for basic type inference has proven to be a challenge with limited helpful information found in documentation or online searches. My goal is to create a function inferType that can determine and return the inferred ...
Currently, I am working with lerna and everything runs smoothly locally. However, when I attempt to build the image and operate it through Docker, it does not function as expected. FROM node:16-alpine3.11 ENV NODE_ENV=production COPY . /app WORKDIR /app R ...
Encountering an issue with fowardRef in ReactJS where everything seems fine, but an error pops up: Type '{ children: Element; ref: MutableRefObject<HTMLDivElement>; }' is not assignable to type 'IntrinsicAttributes & SectionContent ...
A similar question has been asked previously, however... I am looking to enhance my color options by adding variants such as success, warning, and more choices within the background category (palette.background). Specifically interested in a lite option t ...