Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is `export type` in Typescript?

I notice the following syntax in Typescript.

export type feline = typeof cat;

As far as I know, type is not a built-in basic type, nor it is an interface or class. Actually it looks more like a syntax for aliasing, which however I can't find reference to verify my guess.

So what does the above statement mean?

like image 976
hackjutsu Avatar asked May 19 '17 22:05

hackjutsu


People also ask

Can we export type in TypeScript?

Use a named export to export a type in TypeScript, e.g. export type Person = {} . The exported type can be imported by using a named import as import {Person} from './another-file' . You can have as many named exports as necessary in a single file.

What is export type in react?

Introduction. Importing and exporting in React JS will help us write modular code, i.e., splitting code into multiple files. Importing allows using contents from another file, whereas exporting makes the file contents eligible for importing.

How do I export a TypeScript method?

Yes, we can export the functions in TypeScript by using the 'export' keyword at the start of the function. export interface inteface_name: In TypeScript, we can export the interface as well, we can follow this syntax to make the interface exportable.

How do you use export classes in TypeScript?

Use named exports to export multiple classes in TypeScript, e.g. export class A {} and export class B {} . The exported classes can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a file.


1 Answers

This is a type alias - it's used to give another name to a type.

In your example, feline will be the type of whatever cat is.

Here's a more full fledged example:

interface Animal {
    legs: number;
}

const cat: Animal = { legs: 4 };

export type feline = typeof cat;

feline will be the type Animal, and you can use it as a type wherever you like.

const someFunc = (cat: feline) => {
    doSomething(cat.legs);
};

export simply exports it from the file. It's the same as doing this:

type feline = typeof cat;

export {
    feline
};
like image 160
James Monger Avatar answered Oct 16 '22 19:10

James Monger