Home > Blockchain >  In TypeScript what is the difference between 'export type' and 'export declare type&#
In TypeScript what is the difference between 'export type' and 'export declare type&#

Time:09-16

In TypeScript I thought the 'declare' hints to the compiler that this is created somewhere else. How do these two "types" that appear to work the same actually differ. Is it because if it doesn't find it anywhere else it uses the current one?

EXAMPLE:

SomeTypes.ts

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

Both have 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 acceptably declared

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

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

CodePudding user response:

Absolutely nothing. declare simply states that the member your are declaring is in an ambient context. The "ambient context" basically just means that it does not matter for runtime, it's just for typing. Therefore, types and interfaces are already in an ambient context so it doesn't change anything.

  • Related