What is the reason behind typescript not needing `undefined` with the ?: operator on arrays?

type Artifact = {
    a:string
}

const items : Artifact[] = [];

// this will result in a syntax error
let z?: Artifact;

// assigning undefined to a variable of type Artifact is an error
const b : Artifact = undefined;

// despite expectations, this assignment works but might lead to issues with possibly undefined values
const c : Artifact = items?.[0];

// These assignments work as intended.
const a : Artifact|undefined = undefined;
const d : Artifact|undefined = items?.[0];

Playground

Answer №1

There is a constant evolution of items in your code, rendering the use of "?" as invalid

I expanded upon your illustration to display all possible variations Playground Link

const items: Artifact[] | undefined = [];
const undefinedItems: Artifact[] | undefined = undefined;
function getItems(): Artifact[] | undefined {
    return [];
}
const c0 : Artifact = items[0];
const c1 : Artifact = items?.[0];
const c2 : Artifact = undefinedItems?.[0];
//    ^ Type 'undefined' is not assignable to type 'Artifact'
const c3 : Artifact = getItems()[0];
//                    ^ Object is possibly 'undefined'.
const c4 : Artifact = getItems()?.[0];
//    ^ Type 'Artifact | undefined' is not assignable to type 'Artifact'

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

Tips for implementing assertions within the syntax of destructuring?

How can I implement type assertion in destructuring with Typescript? type StringOrNumber = string | number const obj = { foo: 123 as StringOrNumber } const { foo } = obj I've been struggling to find a simple way to apply the number type assertio ...

Strategies for preventing profanity in Typescript within Nuxt 2 implementation

implement user authorization functionality create the Auth class for authentication handling import type { Context } from '@nuxt/types'; export class Auth { public ctx: Context; constructor(ctx: Context) { t ...

How to extract the chosen option from a bound list within an Angular application

Our goal is to avoid using 2-way binding in our component setup: <select type="text" formControlName="region" (change)="regionChanged($event)"> <option *ngFor="let region of regionsDDL" [ngValue]="region">{{region.name}}</option> ...

Create a configuration featuring filter options similar to Notion's functionality

The objective is to create a system that can establish certain constraints, similar to the way Notion handles filter properties. https://i.sstatic.net/plctW.png System A sets up the constraints and System C evaluates them, both using Typescript. However, ...

How can we use Angular Table to automatically shift focus to the next row after we input a value in the last cell of the current row and press the Enter key

When the last cell of the first row is completed, the focus should move to the next row if there are no more cells in the current row. <!-- HTML file--> <tbody> <tr *ngFor="let row of rows;let i=index;" [c ...

Receiving a conduit from the fuel supplier with only limited information on hand

I am designing a service that will utilize pipes as templates. In order to accomplish this, I require access to the registered pipes. The final code structure should resemble the following: @Injectable() class MyService { constructor(private injector ...

No declaration file was found for the module named 'vue2-timepicker'

Overview I integrated the vue2-timepicker plugin into my Typescript/Nuxt.js application. However, I encountered an issue with importing vue2-timepicker. import timepicker from 'vue2-timepicker' Could not find a declaration file for module &apos ...

What is the best way to create an instance method in a subclass that can also call a different instance method?

In our programming project, we have a hierarchy of classes where some classes inherit from a base class. Our goal is to create an instance method that is strongly-typed in such a way that it only accepts the name of another instance method as input. We d ...

Develop a query builder in TypeORM where the source table (FROM) is a join table

I am currently working on translating this SQL query into TypeORM using the QueryBuilder: SELECT user_places.user_id, place.mpath FROM public.user_root_places_place user_places INNER JOIN public.place place ON place.id = user_places.place_id The ...

Exploring TypeAhead functionality in Reactjs 18

I have encountered an issue while using react-bootstrap-typeahead version 5.1.8. The problem arises when I try to utilize the typeahead feature, as it displays an error related to 'name'. Below is my code snippet: import { Typeahead } from " ...

Encountering multiple error messages from Protractor @types

Lately, I've been using the Angular2 Webpack Starter created by AngularClass and I've started encountering some perplexing errors with Protractor. When trying to build, these errors pop up: Module 'webdriver' has no exported member &ap ...

Error: Unable to access the 'filter' property as it is undefined. TypeError occurred

findLoads(){ if(this.loggedInUser.userFullySetupFlag === 0 || this.loggedInUser.businessFullySetupFlag === 0){ swal( 'Incomplete Profile', 'To find loads and bid, all the details inside User Profile (My Profile) and Business Profil ...

Having trouble with Typescript subtraction yielding unexpected results?

If I have a total amount including VAT and want to separate the net price and the VAT value, how can this be done? For example, if the final price is $80.60 with a VAT rate of 24%, what would be the net price and the VAT value? The correct answer should ...

Discrepancy between code, output from ng build, and how the browser is

I am in the process of developing an Angular 13 library that includes two services and a group of models. These services consist of an authentication service and a client service. However, after building the library, I noticed some global variables missing ...

Encountering an Error: Unforeseen Token < Causing Webpack Configuration Problem in Typescript

Seeking assistance to resolve an issue that has arisen while working on a project with Typescript, React, and Webpack. I referred to the guide available at https://www.typescriptlang.org/docs/handbook/react-&-webpack.html After configuring everything, ...

Typescript Error:TS2345: The argument '{ theme: string; jsonFile: string; output: string; }; }' is not compatible with the parameter type 'Options'

Encountering an error mentioned in the title while using the code snippet below: import * as fs from 'fs' import { mkdirp } from 'mkdirp' import * as report from 'cucumber-html-reporter' const Cucumber = require('cucumber ...

Having trouble retrieving the Ionic 2 slides instance - getting a result of undefined

As I attempt to utilize the slides and access the instance in order to use the slideto functionality programmatically, I find myself encountering the issue of receiving 'undefined' back despite following the documentation. Here is my TypeScript ...

Troubleshooting an angular problem with setting up a dynamic slideshow

I am currently working on building a slideshow using plain HTML, CSS, and JavaScript. I referred to the following example for guidance: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto However, despite implementing the code prov ...

Type of event triggered by user file upload via INPUT element

I have a piece of code that reads the contents of a locally stored file. Here is what it looks like: onFile(event: any) { console.log(event); const file = event.target.files[0]; const reader = new FileReader(); reader.onloadend = (ev: any) => { ...

Leverage the power of TypeScript with knockout's pureComputed function

I am facing an issue with referencing the this object in a function called problem: const c = { f() { console.log("hi"); }, problem: ko.pureComputed(() => { return this.f(); }), }; [ts] The containing arrow function captures the glob ...