Вот минимальный пример. Наша структура каталогов будет следующей: < /p>
Код: Выделить всё
test
├── package-lock.json
├── package.json
├── test.ts
├── tsconfig.json
├── dist
│ ├── index.d.ts
│ └── index.js
└── lib
├── index.ts
└── types.d.ts
< /code>
Вот содержимое файлов: < /p>
package.json
Код: Выделить всё
{
"name": "test",
"version": "1.0.0",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"author": "",
"license": "ISC",
"description": ""
}
< /code>
tsconfig.json
Код: Выделить всё
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"declaration": true,
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"include": ["lib/**/*"]
}
< /code>
lib/types.d.ts
Код: Выделить всё
declare namespace MyTypes {
interface Bar {
a: string;
}
interface SecondBar {
a: number;
}
}
< /code>
lib/index.ts
Код: Выделить всё
function foo(bar: MyTypes.Bar): string;
function foo(bar: MyTypes.SecondBar): number;
function foo(bar: MyTypes.Bar | MyTypes.SecondBar): number | string {
if (typeof bar.a === "string") {
return "0";
}
return 1;
}
const MyModule = { foo };
export default MyModule;
< /code>
Thus, our module will export a function that will have two different return value types depending on the type of its single argument.
The problem here is that when we use TypeScript to compile the library, the type declaration file is not included in the result, so the MyTypes
Итак, если мы попробуем библиотеку: (файл test.ts )
Код: Выделить всё
import MyModule from "./dist";
const result = MyModule.foo({ a: "string" })
// result will be a string but will be considered by TypeScript as a number
< /code>
Thus, result
Подробнее здесь: https://stackoverflow.com/questions/796 ... led-npm-pa