Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring interfaces in separate files

Tags:

typescript

Say I have a file user.ts that has the following declaration:

export interface User {
  userName: string;
}

I want to import this interface from another ts script, but since JavaScript doesn't support interfaces the transpiler wouldn't produce the user.js and I'm getting an error on import.

Of course, I could declare User as a class as a workaround, but is there a way to declare an interface in a separate TypeScript file?

like image 538
Yakov Fain Avatar asked Feb 18 '16 19:02

Yakov Fain


1 Answers

You can try making the user file have the .d.ts extension.

For example:

user.d.ts

export interface User {
    name: string
}

and you can import it as usual:

someotherfile.ts

import {User} from './user';
    
function check(user: User) {
    if (user.name) {
        console.log('yeey works');
    }
}

check({ name: 'ion' });
like image 87
toskv Avatar answered Sep 25 '22 10:09

toskv