Are union types strictly enforced?

Is it expected for this to not work as intended?

class Animal { }
class Person { }

type MyUnion = Number | Person;

var list: Array<MyUnion> = [ "aaa", 2, new Animal() ]; // Is this supposed to fail?

var x: MyUnion = "jjj"; // Should this actually pass?

Any suggestions on how to enforce strict type checking in this scenario?

Answer №1

When it comes to TypeScript, type compatibility is determined by structural subtyping.

Structural typing focuses on the members of types, rather than their names or declarations.

Specifically for classes:

Comparing two objects of a class type in TypeScript involves only comparing the members of the instance, without considering static members or constructors.

For further details, check out https://www.typescriptlang.org/docs/handbook/type-compatibility.html#classes

Answer №2

If there is any definition within Animal or Person, the following will not work:

class Animal { type: string; }
class Person { profession: string; }

type MyCombine = string | Person;

var collection: Array<MyCombine> = [ "apple", 3, new Animal() ]; // Currently leads to failure

var y: MyCombine = "orange"; // Currently leads to failure

In the absence of any declarations in Animal or Person, a string (or any other data) meets the criteria you are seeking.

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

What is the most effective way to sort a list using Angular2 pipes?

I'm currently working with TypeScript and Angular2. I've developed a custom pipe to filter a list of results, but now I need to figure out how to sort that list alphabetically or in some other specific way. Can anyone provide guidance on how to a ...

Eliminate the usage of JSON.stringify in the Reducer function

I have a system where I store chat messages in a dictionary with the date as the key and a list of messages as the value. Whenever a new message is added, the following code snippet is executed. Is there a way to enhance the existing code to eliminate the ...

Navigating through a node tree and making changes to its configuration and content

Here's the input I have. Some nodes have downlines with multiple other nodes nested inside. data = [ { "user_id": "1", "username": "johndoe001", "amount": "0.00", "down ...

Could you please share the standard naming convention used for interfaces and classes in TypeScript?

Here's what I have: interface IUser { email: string password: string } class User { email: string password: string constructor(email: string, password: string) { this.email = email this.password = password } isEmailValid(): boo ...

The server's response is unpredictable, causing Json.Parse to fail intermittently

I have encountered a strange issue that is really frustrating. It all started when I noticed that my Json.Parse function failed intermittently. Here is the code snippet in question: const Info = JSON.parse(response); this.onInfoUpdate(Info.InfoConfig[0]); ...

The ListView is not updating correctly as expected

Currently, I am working on a project where I have a Page with a ListView that displays items from an ObservableArray of Expense objects. The issue I am facing is that when I scroll down, the amount property of some Expense rows is not being displayed. Howe ...

Unable to access due to CORS restriction on Express server

Whenever I attempt to send a POST api request to my express server, I encounter the following error message. Access to XMLHttpRequest at 'localhost:8081/application' from origin 'localhost:8083' has been blocked by CORS policy: No &apos ...

Encountered 'DatePickerProps<unknown>' error while attempting to develop a custom component using Material-UI and react-hook-form

Currently, I'm attempting to create a reusable component using MUI Datepicker and React Hook Form However, the parent component is throwing an error Type '{ control: Control<FieldValues, object>; name: string; }' is missing the follow ...

Utilize a combination of generic parameters as the keys for objects in TypeScript

Is there a method to utilize multiple generic parameters as object keys in TypeScript? I came across this answer which works well when there is only one parameter, but encounters issues with more than one. The error message "A mapped type may not declar ...

The Child/Parent arguments in Typescript methods cannot be assigned

Why is this not working in TypeScript? class Parent { id: string = '' } class Child extends Parent{ name: string = '' } const fails: (created: Parent) => void = (created: Child) => { return }; const failsToo: ({ create ...

Updating a one-to-one relationship in TypeORM with Node.js and TypeScript can be achieved by following these steps

I am working with two entities, one is called Filter and the other is Dataset. They have a one-to-one relationship. I need help in updating the Filter entity based on Dataset using Repository with promises. The code is written in a file named node.ts. Th ...

Using a React component with Material-UI style classes in TypeScript is not possible

Recently delving into react, I've embarked on a learning project utilizing typescript 3.7.2 alongside material-ui 4.11.0 and react 16.13.1. Initially, I structured my page layouts using functional components, but upon attempting to switch them to clas ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Tips for implementing a reusable instance of a class in (SSR) React (comparable to a @Bean in Spring)

I am currently developing a new application using Next.js and React (Server Components) in TypeScript. In order to showcase and evaluate the app, I need to support two different data sources that provide identical data through separate APIs. My goal is to ...

What could be the reason for `process.env.myvariable` not functioning in a Next.js project with TypeScript

After creating a file called .env.local in the root directory of my project, I added a variable called WEBSOCKET_VARIABLE=THIS_IS_TEXT to it. However, when I try to access it using process.env.WEBSOCKET_VARIABLE, nothing is found. What could be causing ...

The phrase 'tsc' is not identified as a valid cmdlet, function, script file, or executable program

Recently, I attempted to compile a TypeScript file into a JavaScript file by installing Node.js and Typescript using the command "npm install -g typescript". However, when I tried to compile the file using the command tsc app.ts, an error occurred: tsc : T ...

Deciding between bundling a Typescript package and using tsc: When is each approach the best choice

When it comes to publishing a Typescript NPM package (library, not client), I have two main options: 1. Leveraging Typescript's compiler First option is to use the Typescript compiler: tsc and configure a tsconfig.json file with an outDir setting: { ...

Error: Unable to locate Angular2 Custom Service

I have implemented a custom service to populate a list of people in my HTML. Below is the code for my custom service: app.peopleListService.ts import { Injectable } from '@angular/core'; import { Person } from "../model/peopleModel"; @Injecta ...

Parallel Execution Issue with RxJS Observable forkJoin

Struggling to understand why my requests aren't executing concurrently with the following code. As a newcomer to RxJS and observables, I would greatly appreciate any guidance on improving this snippet below. Essentially, I am fetching data from a REST ...

mat-table dataSource is not functioning properly with REST API integration

I'm facing an issue while trying to populate a Material Table with data. My model Block has fields such as id, date, etc. The API call is made in data.service and the function getAllBlock() fetches the blocks. I tested this in the app.component.html ...