TypeScript의 "*.d.ts"에 대해서
는 금궁이 ..d.tsTypeScript 프로그래밍 언어에 익숙하지 않기 때문에 선언 파일을 사용합니다.에게 '아주 좋다'는 말을 ..d.ts요..h, C++ 입니다..d.ts파일이 완전히 동일하게 동작하지 않는 것 같습니다.현재 .d.ts 파일을 올바르게 사용하는 방법을 이해하지 못하고 있습니다. 말을 수 것 ..js ★★★★★★★★★★★★★★★★★」.ts을 송신합니다..d.ts이 세 가지 파일 유형이 모두 포함되어 있어야만 프로젝트가 작동합니다.★★★★★★★★★★★★★★★★★★★★★★★★★★★이 JavaScriptTypeScript와 되어 있는지 몇 d.ts JavaScript type TypeScript 。
이 세 파일의 관계는 무엇입니까?어떤 관계일까요?
어떻게 하면
*.d.ts요?*.ts★★★★★★★★★★★★★★★★?하면 요?
*.d.ts어떤 JS 파일이 자신에게 매핑되는지 알 수 있습니까?
누가 예를 들어주면 좋을 것 같아요.
"d.ts" 파일은 JavaScript로 작성된 API에 대한 유형 정보를 제공하기 위해 사용됩니다.jQuery나 언더스코어(기존 Javascript 라이브러리) 같은 것을 사용하는 것이 목적입니다.타이프스크립트 코드에서 그것들을 소비하려고 합니다.
jquery나 언더스코어 등을 타이프 스크립트에 다시 쓰는 대신 타입 주석만 포함된 d.ts 파일을 쓸 수 있습니다.그런 다음 순수 JS 라이브러리를 사용하면서도 타이프스크립트 코드에서 스태틱타이프 체크의 이점을 얻을 수 있습니다.
은 TypeScript의할 수 import할 때 를 들어 '파일을 참조할 때'라고 my-module.js「」가 my-module.d.ts그 합니다.「 TypeScript 」 。
src/
my-module.js
my-module.d.ts
index.ts
my-displaces.displaces
const thing = 42;
module.exports = { thing };
my-backets.d.ts
export declare const thing: number;
인덱스.ts
import { thing } from "./my-module"; // <- no extension
// runtime implementation of `thing` is taken from ".js"
console.log(thing); // 42
// type declaration of `thing` is taken from ".d.ts"
type TypeOfThing = typeof thing; // number
dDeclaration Files(선언 파일):
TypeScript 스크립트가 컴파일되면 컴파일된 JavaScript 컴포넌트에 대한 인터페이스로서 기능하는 선언 파일(확장자 .d.ts)을 생성하는 옵션이 있습니다.이 과정에서 컴파일러는 모든 함수 및 메서드 본문을 제거하고 내보내는 유형의 시그니처만 유지합니다.그 결과 생성된 선언 파일은 서드파티 개발자가 TypeScript에서 JavaScript 라이브러리 또는 모듈의 내보내기된 가상 TypeScript 유형을 설명하는 데 사용할 수 있습니다.
선언 파일의 개념은 C/C++에 있는 헤더 파일의 개념과 유사합니다.
declare module arithmetics {
add(left: number, right: number): number;
subtract(left: number, right: number): number;
multiply(left: number, right: number): number;
divide(left: number, right: number): number;
}
jQuery 및 Node.js와 마찬가지로 기존 JavaScript 라이브러리에 대해 형식 선언 파일을 수동으로 작성할 수 있습니다.
인기 있는 JavaScript 라이브러리를 위한 많은 선언 파일 컬렉션은 확실히 GitHub에서 호스트됩니다.및 타이핑 레지스트리를 입력.저장소에서 선언 파일을 검색하고 설치하는 데 도움이 되는 타이핑이라는 명령줄 유틸리티가 제공됩니다.
나는 자바스크립트 프로젝트를 힘들게 매핑하면서 다음을 배웠다..d.tsfiles.complete files files files files files files files files.
「」의 .d.ts..d.ts 한 파일.js 파일.js은 같은 디렉토리에 상태로 ..d.ts같은 이름을 가진 파일입니다.JS/TS 의 한 JS..d.ts을 송신합니다..d.tsfiles.complete files files files files files files files files.
::test.js ★★★★★★★★★★★★★★★★★」test.d.ts testdir/폴더를 선택한 후 반응 컴포넌트에 다음과 같이 Import합니다.
import * as Test from "./testdir/test";
.d.ts파일을 다음과 같은 네임스페이스로 내보냈습니다.
export as namespace Test;
export interface TestInterface1{}
export class TestClass1{}
특정 케이스의 작업 예:
npm을 통해 공유하는 my-module이 있다고 칩시다.
를 사용하여 설치한다.npm install my-module
다음과 같이 사용합니다.
import * as lol from 'my-module';
const a = lol('abc', 'def');
의 논리는 '모듈의 논리'에 있습니다.index.js:
module.exports = function(firstString, secondString) {
// your code
return result
}
.index.d.ts:
declare module 'my-module' {
export default function anyName(arg1: string, arg2: string): MyResponse;
}
interface MyResponse {
something: number;
anything: number;
}
예를 들어 @takeshin said .d는 typescript (.ts)의 선언 파일을 나타냅니다.
이 투고에 답변하기 전에 명확히 해야 할 사항은 다음과 같습니다.
- Typescript는 javascript의 구문적 슈퍼셋입니다.
- 타이프스크립트 자체 실행이 아니라 javascript(javascript 변환으로 타이프스크립트)로 번역해야 합니다.
- "유형 정의" 및 "유형 검사"는 javascript에서 제공하는 주요 추가 기능입니다.(type script와 javascript의 차이 확인)
타이프 스크립트가 구문적인 슈퍼셋일 경우 어떤 이점이 있는지 - https://basarat.gitbooks.io/typescript/docs/why-typescript.html#the-typescript-type-system
이 투고에 답변하려면 -
말씀드린 바와 같이 typescript는 javascript의 슈퍼셋이므로 javascript로 번역해야 합니다.따라서 라이브러리나 서드파티 코드가 타이프스크립트로 작성되면 결국 javascript로 변환되어 javascript 프로젝트에서 사용할 수 있지만 그 반대는 해당되지 않습니다.
ex-
javascript 라이브러리를 설치하는 경우 -
npm install --save mylib
타이프스크립트 코드로 Import를 시도합니다.
import * from "mylib";
에러가 납니다.
"'mylib' 모듈을 찾을 수 없습니다."
@Chris에서 언급했듯이 언더스코어, Jquery와 같은 많은 라이브러리는 이미 javascript로 작성되어 있습니다.타이프스크립트 프로젝트를 위해 라이브러리를 다시 쓰는 대신 대체 솔루션이 필요했습니다.
이를 위해 위의 mylib.d.ts와 같이 *.d.ts라는 이름의 javascript 라이브러리에 type declaration 파일을 제공할 수 있습니다.선언 파일은 각 Javascript 파일에 정의된 함수 및 변수의 형식 선언만 제공합니다.
이제 시도하면...
import * from "mylib";
mylib.d.ts는 javascript 라이브러리 코드와 typescript 프로젝트 사이의 인터페이스로 기능하는 Import 됩니다.
하지 않는 을 전제로 하고 만, 체크를 해, JavaScript의 으로 억제하고 .다만, 타입 체크를 최소한으로 해 주세요..js.A.A.d.tsC++는 C++로 하다.그 목적은 인터페이스를 정의하는 것입니다.하다
mashString.d.ts
/** Makes a string harder to read. */
declare function mashString(
/** The string to obscure */
str: string
):string;
export = mashString;
mashString.js
// @ts-check
/** @type {import("./mashString")} */
module.exports = (str) => [...str].reverse().join("");
main.discloss.main.discloss.
// @ts-check
const mashString = require("./mashString");
console.log(mashString("12345"));
는 다음과 같습니다.mashString.d.ts 「」를 합니다.mashString.js와 ""를 합니다.main.js는 인터페이스를 사용합니다.
시키려면 , 「」를 합니다.// @ts-checkyour .js이 파일만 합니다. 하지만 이것은 단지main.js을 사용하다또한 다음 사항을 확실히 하기 위해mashString.js하다, 라고 덧붙입니다./** @type {import("./mashString")} */수출 전에
수 ..d.ts, ""」를 사용한 파일tsc -allowJs main.js -d그런 다음 필요에 따라 수동으로 편집하여 유형 확인 및 문서화를 개선합니다.
는 같은.여기서는 「」라고 합니다.여기서 설명하겠습니다.mashString그러나 다른 구현이 가능합니다.를 들어, 는 이름을 수 있습니다.mashString.js로로 합니다.reverse.js 다른 .encryptString.js.
여기에 내 2센트를 더하면 될 것 같아
// somefile.d.ts
export type SomeItem = {
weight: number
}
export type ItemStorage = {
name: string
items: SomeItem[]
}
// somefile.js
// @ts-check
/** @typedef { import('./somefile.d.ts').SomeItem } SomeItem */
/** @typedef { import('./somefile.d.ts').ItemStorage } ItemStorage */
/**
* @param { StorageItem } item
*/
function doSomething(item) {
item. // intellisense
// your code here
}
여기서 깔끔한 점은 기존 자바스크립트 프로젝트에 조금씩 활자를 넣을 수 있다는 것이다.
공식 문서(https://www.typescriptlang.org/docs/handbook/2/type-declarations.html#dts-files):
.d.ts파일이 파일들은 .js 출력을 생성하지 않고 형식 확인에만 사용됩니다.
소스코드가 진실의 최종 소스이기 때문입니다.이를 위한 구현은 다음과 같습니다.
/*
* Every module resolution kind can has its specific understanding how to load module from a specific path on disk
* I.e. for path '/a/b/c':
* - Node loader will first to try to check if '/a/b/c' points to a file with some supported extension and if this fails
* it will try to load module from directory: directory '/a/b/c' should exist and it should have either 'package.json' with
* 'typings' entry or file 'index' with some supported extension
* - Classic loader will only try to interpret '/a/b/c' as file.
*/
type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState) => Resolved | undefined;
그리고.
/**
* Kinds of file that we are currently looking for.
*/
const enum Extensions {
TypeScript = 1 << 0, // '.ts', '.tsx', '.mts', '.cts'
JavaScript = 1 << 1, // '.js', '.jsx', '.mjs', '.cjs'
Declaration = 1 << 2, // '.d.ts', etc.
Json = 1 << 3, // '.json'
ImplementationFiles = TypeScript | JavaScript,
}
전체 파일은 https://github.com/microsoft/TypeScript/blob/main/src/compiler/moduleNameResolver.ts 입니다.
예를 들어, npm부터 'alertifyjs' 모듈을 사용하는 데 문제가 발생했습니다.
- 'anyName'을 만듭니다.You like.d.ts' (예: 이 파일을 src 폴더에 작성)
- 파일에 모듈 'alertifyjs'를 선언합니다. 여기에 이미지 설명을 입력하십시오.
- tsconfig.json의 "compilerOptions" "typeRoots" : ["node_modules/@types", "src/anyName"마음에 들어요.d.ts"]
언급URL : https://stackoverflow.com/questions/21247278/about-d-ts-in-typescript
'programing' 카테고리의 다른 글
| 식 변수 앞의 이중 콜론은 각도 js에서 무엇을 합니까? (0) | 2023.02.27 |
|---|---|
| java.displaces를 클릭합니다.ClassNotFoundException: org.springframework.web.servlet.디스패처 서블릿 (0) | 2023.02.27 |
| Github Wiki에서 JSON 블록을 스타일링하는 방법 (0) | 2023.02.27 |
| WP Job Manager - 작업 목록 추가를 위한 등록 흐름 변경 (0) | 2023.02.27 |
| @ExtendWith(SpringExtension.class)와 @ExtendWith(MockitoExtension.class)의 차이점은 무엇입니까? (0) | 2023.02.27 |