{package.json“清单文件的TypeScript类型声明?

时间:2019-07-26 11:47:11

标签: typescript npm typescript-typings package.json type-declaration

在TypeScript中键入“ package.json”清单文件内容的最佳方法是什么?

import { promises as fs } from 'fs';

export function loadManifest(): Promise<any> {

  const manifestPath = `${PROJECT_DIR}/package.json`;

  return fs.readFile(manifestPath, { encoding: 'utf-8' });

}

在上面的示例中,我必须使用Promise<any>作为返回类型。但是,还有更好的方法吗?也许某个发布在我找不到的地方的软件包?

2 个答案:

答案 0 :(得分:1)

https://www.npmjs.com/package/package-json-type

import {
  IDependencyMap,
  IEngines,
  IPackageJson,
  SPDXLicenseIDApproved
} from 'package-json-type';
 
const dependency: IDependencyMap = {
  bar: '^1.0.0',
  baz: '^2.1.0',
  qux: 'file:../src/qux'
};
 
const engines: IEngines = {
  node: '>=6.0.1 <11.0.0',
  yarn: '^1.15.0',
  zlib: '^0.14.0'
};
 
const license: SPDXLicenseIDApproved = 'MIT';
 
const pkg: IPackageJson = {
  name: 'foo',
  version: '1.2.3',
  dependency,
  description: 'This is awesome foo',
  engines,
  license 
};

答案 1 :(得分:0)

有一个issue for that in DefinitelyTyped。最后一条注释指向@schemastore/package。在那里使用的类型定义似乎是正确的。

安装软件包后,您可以像这样使用它:

import { promises as fs } from 'fs';
import {JSONSchemaForNPMPackageJsonFiles} from '@schemastore/package';

export function loadManifest(): Promise<JSONSchemaForNPMPackageJsonFiles> {
  const manifestPath = `${PROJECT_DIR}/package.json`;
  return fs.readFile(manifestPath, { encoding: 'utf-8' }) as Promise<any>;

}