programing

타입 스크립트인터페이스를 다른 파일로 선언 및 Import하는 방법

bestprogram 2023. 3. 28. 22:46

타입 스크립트인터페이스를 다른 파일로 선언 및 Import하는 방법

타이프 스크립트 기반 프로젝트에서 자체 파일에 여러 개의 인터페이스를 정의하고 프로덕션용 클래스 및 테스트용 머크를 구현합니다.그러나 올바른 구문이 무엇인지 알 수 없습니다.인터페이스의 선언과 실장에 관한 튜토리얼은 많이 있습니다만, 모두 같은 파일에 인터페이스와 파생 클래스를 간단하게 실장하고 있기 때문에 현실성이 없습니다.인터페이스를 내보내고 가져오는 올바른 방법은 무엇입니까?

정의된 파일에서 인터페이스를 내보내고 원하는 위치에 Import해야 합니다.

IfcSampleInterface.ts:

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

SampleInterface.ts

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

정의 사용(d.ts) 파일 및 네임스페이스.이러한 방법으로 모듈을 Import/export 할 필요가 없습니다.물론입니다유형화된 프로젝트에는 지침과 수많은 예제있습니다.

일부 인터페이스만 내보냅니다.

여러 개의 내보내기를 분산시키지 않고 단일로 그룹화할 수 있습니다.export {}block(이 경우 파일 형식을 선언하지 않음):

// 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 예시

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)
};

비교적 새로운 프로젝트에서 다음 구문을 사용할 수 있습니다.

`import type { xxx } from './xxx'`

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html

에서 정의되어 있는 파일 내의 인터페이스를 내보내고 사용되는 파일로 Import해야 합니다.예에 대해서는, 이 링크를 참조해 주세요.

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 를 참조해 주세요.

언급URL : https://stackoverflow.com/questions/37263357/how-to-declare-and-import-typescript-interfaces-in-a-separate-file