简体   繁体   中英

Custom npm package in typescript: cannot find name of custom interface

I have angular app in typescript built with webpack. Also I have npm package (hosted in Sinopia not npm) with next structure

my-custom-npm-package
- index.ts
- studentStorage.ts
- student.d.ts

student.d.ts

interface IStudent
{
    name: string;
    id: number;
}

index.ts

import { StudentStorage } from './studentStorage';
export { StudentStorage }

studentStorage.ts

export class StudentStorage{
    private students: IStudent[] = [];

    public get(): IStudent[]{
        return this.students.slice(0);
    }   
}

In my angular component I have this string

import { StudentStorage } from 'my-custom-npm-package';

Next I get this error with webpack

ERROR in D:\Sandbox\MultiLanguage\node_modules\my-custom-npm-package\studentStorage.ts
(2,23): error TS2304: Cannot find name 'IStudent'.

I have workaround: Create typings.d.ts where I write

/// <reference path="node_modules/my-custom-npm-package/student.d.ts" />

But I want to use my custom npm package without this fix. I want installation without referencing .d.ts files.

How can I achieve this?

One solution would probably be to add /// <reference path="student.d.ts" /> to studentStorage.ts . But it's weird to have IStudent global while the rest of your library is in modules. I'd suggest making student.d.ts into a module by changing it to:

export interface IStudent
{
    name: string;
    id: number;
}

and studentStorage.ts to:

import { IStudent } from "./student";
export class StudentStorage{
    private students: IStudent[] = [];

    public get(): IStudent[]{
        return this.students.slice(0);
    }   
}

Then clients of your library that want to use IStudent will just have to import it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM