What sets apart 'export type' from 'export declare type' in TypeScript?

When using TypeScript, I had the impression that 'declare' indicates to the compiler that the item is defined elsewhere. How do these two seemingly similar "types" actually differ? Could it be that if the item is not found elsewhere, it defaults to the current one?

EXAMPLE:

SomeTypes.ts

export type FooBarType = 'Foo' | 'Bar';
export declare type FooBarDeclareType = 'Foo' | 'Bar';

Both trigger the expected IDE warnings:

Type "This is not foo or Bar" is not assignable to type 'FooBarType'

import SomeTypes.ts

const getFooOrBarType_expectedWarnings = (): FooBarType => 'This is not foo or Bar'; 
const getFooOrBarDeclareType_expectedWarnings = (): FooBarDeclareType => 'This is not foo or Bar'; 

Both 'foo' and 'bar' are correctly declared

const getFooOrBarType_bar = (): FooBarType => 'Bar'; 
const getFooOrBarDeclareType_bar = (): FooBarDeclareType => 'Bar'; 

const getFooOrBarType_foo = (): FooBarType => 'Foo'; 
const getFooOrBarDeclareType_foo = (): FooBarDeclareType => 'Foo'; 

Answer №1

In essence, declaring something in TypeScript with the keyword declare signifies that the declared element exists in an ambient context. This "ambient context" specifically pertains to its role in typing rather than affecting runtime behavior. As a result, types and interfaces are inherently considered to be in an ambient context by default, rendering the use of `declare` redundant in such scenarios.

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

Typescript raises a error notification regarding the absence of a semicolon when importing a JSON module

Attempting to import a local JSON object into my Vuex store using const tree = import('@/articles/tree.json');. The setting "resolveJsonModule": true, has been enabled in my tsconfig.json and it loads successfully, however NPM is flooding the out ...

Utilize Angular 9 to fetch data from an API using the Get method, map them to a class, and

Seeking to extract information from a test URL and convert the data into a list, I aim to exhibit them in an alert/Loop for testing purposes. The dummy API URL being used is: The returned data follows this structure: {"status":"success","data":[{"id":"1" ...

Issue encountered while setting up controls and AbstractControls in form development

Here is a snippet of code showing how I create and manipulate a form in Angular: this.myForm = new FormGroup({ points: new FormArray([ new FormGroup({ date: this.date, startTime: new FormControl(null, Val ...

Trouble encountered when utilizing [ngClass] - Error occurred due to changes in expression after it has been checked

I keep encountering an error when attempting to utilize [ngClass] in my Angular project. The specific error message I receive is as follows: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ' ...

Puzzled by the specialized link feature

As I delve into the world of React and Next.js, I find myself working on the link component. Initially, I had a grasp on basic routing in next.js which seemed pretty straightforward. However, things took a confusing turn when I stumbled upon this code: imp ...

How can I display the values stored in an array of objects in Angular 2

I need help printing out the value of id from an array that is structured like this: locations = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)'}, {id: '2', lat: 51.523 ...

Issue with the height not being updated in a parent React nested Accordion

Currently, I am in the process of developing the mobile version of my homepage. However, there seems to be a bug in my nested accordion labeled "Projects." The bug is causing an issue where the bottom projects section does not display at the correct height ...

The parseFloat function only considers numbers before the decimal point and disregards

I need my function to properly format a number or string into a decimal number with X amount of digits after the decimal point. The issue I'm facing is that when I pass 3.0004 to my function, it returns 3. After reviewing the documentation, I realized ...

Need to import Vue component TWICE

My question is simple: why do I need to import the components twice in the code below for it to function properly? In my current restricted environment, I am unable to utilize Webpack, .vue Single File Components, or npm. Despite these limitations, I mana ...

Different ways to update the AutoComplete Style attribute

MuiInput-formControl { margin-top: 16px; Is there a way to reset the marginTop property to zero? I attempted the following method, but it was not successful. MuiFormControlLabel: { marginTop: 0, }, <Autocomplete disabl ...

The error code TS2345 indicates that the argument type 'Event' cannot be assigned to a parameter type 'string'

Hello, I'm a newcomer to utilizing Angular and I'm struggling to identify where my mistake lies. Below is the TypeScript code in question: import { Component } from '@angular/core'; @Component({ selector: 'app-root' ...

Issue: The element '[object Object]' is of type 'object', which is not supported by NgFor. NgFor only works with Iterables like Arrays. - Problem encountered in an Ionic Project

I'm currently working on retrieving my user's username from Firebase Firestore Database using Ionic and AngularFire. I have implemented the valueChanges() method to obtain the observable and am trying to process it using an async pipe. However, u ...

Sending an event from a child component to another using parent component in Angular

My form consists of two parts: a fixed part with the Save Button and a modular part on top without a submit button. I have my own save button for performing multiple tasks before submitting the form, including emitting an Event to inform another component ...

Axios is causing my Pokemon state elements to render in a jumbled order

Forgive me if this sounds like a silly question - I am currently working on a small Pokedex application using React and TypeScript. I'm facing an issue where after the initial page load, some items appear out of order after a few refreshes. This make ...

Creating objects based on interfaces

After looking at this straightforward code: interface int1 { aa: string, bb: number, } const obj1:int1 = {} //#1 function fun(param_obj:int1) { //#2 } I am curious as to why the compiler throws an error: Type '{}' is missing the fol ...

Accessing an unregistered member's length property in JavaScript array

I stumbled upon this unique code snippet that effectively maintains both forward and reverse references within an array: var arr = []; arr[arr['A'] = 0] = 'A'; arr[arr['B'] = 1] = 'B'; // When running on a node int ...

To ensure the specificity selector for material UI in React, it is essential to include an empty CSS definition

The styling for the unselected toggle button is working smoothly. However, when you don't define an empty class selector, the style of the selected toggle button does not show: ./App.js import * as React from "react"; { render ...

Reacting to shared routes across various layouts

My React application has two layouts: GuestLayout and AuthLayout. Each layout includes a Navbar, Outlet, and Footer, depending on whether the user is logged in: AuthLayout.tsx interface Props { isAllowed: boolean redirectPath: string children: JSX.E ...

Securing Angular 2 routes with Auth Guard through canActivate

I've been searching for a solution to this problem for the past 4 hours with no luck. I have multiple Authguards set up, and I want to instruct the router to grant permission if any of them are true, rather than requiring all guards to be true. Curre ...

Organizing objects into arrays in Node.js

I have an array and I need to concatenate an object after the array. Here is my array: const users = [ {name: "Joe", age: 22}, {name: "Kevin", age: 24}, {name: "Peter", age: 21} ] And here is my object: ...