[typescript] 별도의 파일에서 typescript 인터페이스를 선언하고 가져 오는 방법

필자는 타이프 스크립트 기반 프로젝트에서 자체 파일에 여러 인터페이스를 정의하고 싶습니다. 여기에서 프로덕션 용 클래스와 테스트 용 모의를 구현합니다. 그러나 올바른 구문이 무엇인지 알 수 없습니다. 인터페이스를 선언하고 구현하는 방법에 대한 많은 자습서를 찾았지만 모두 동일한 파일에 인터페이스와 파생 클래스를 모두 사소한 구현으로 포함하고 있으며 이는 실제 환경이 아닙니다. 인터페이스를 내보내고 가져 오는 올바른 방법은 무엇입니까?



답변

정의 된 파일에서 인터페이스를 내보내고 사용하려는 위치에 가져와야합니다.

에서 IfcSampleInterface.ts:

export interface IfcSampleInterface {
   key: string;
   value: string;
}

SampleInterface.ts

import { IfcSampleInterface } from './IfcSampleInterface';
let sampleVar: IfcSampleInterface;


답변

정의 ( d.ts) 파일 및 네임 스페이스를 사용합니다 . 이런 방식으로 모듈을 가져 오거나 내보낼 필요가 없습니다. DefinitelyTyped 프로젝트에는이 를 수행하는 방법에 대한 지침 과 수많은 예제 가 있습니다.


답변

몇 개의 인터페이스 만 내보내기

여러 내보내기를 분산하지 않고 하나의 단일 export {}블록으로 그룹화 할 수 있습니다 (이 경우 파일default 유형을 선언해서는 안 됨).

// interfaces.ts
interface IWords {
  [key: string]: string;
}

interface INumbers {
  [key: string]: number;
}

interface IBooleans {
  [key: string]: boolean;
}

interface IValues {
  [key: string]: string | number;
}

interface IStructures {
  [key: string]: INumbers | IBooleans | IValues;
}

export {
  // not exporting IWords | INumbers
  IBooleans,
  IValues,
  IStructures,
}

가져 오기 예

import { IBooleans, IValues, IStructures } from 'interfaces';

const flags: IBooleans = { read: true, write: false, delete: false };

const userFile: IValues = { user: 1, username: 'One', file: 'types.txt' };

const userContext: IStructure = {
  file: userFile,
  permissions: flags,
  counts: { views: 3, writes: 1 } // => INumbers (lint: try to remove IValues from IStructures)
};


답변

정의 된 파일에서 인터페이스를 내보내고 사용 된 파일에서 가져와야합니다. 예제는이 링크를 참조하십시오.

x.ts

interface X{
    ...
}
export default X

y.ts

import X from "./x.ts"
// You can use X now

자세한 내용은 https://www.typescriptlang.org/docs/handbook/modules.html을 참조 하십시오.


답변