2016-10-04 3 views
2

이와 같이 문서화 된 방법을 사용하여 knockout 정의를 설치했습니다.외부 라이브러리 d.ts에서 선언 된 인터페이스를 확장하는 방법?

npm install @types/knockout 

잘 작동하므로 어디서나 가져올 수 있습니다.

import * as ko from "knockout"; 

그러나 일부 맞춤 구성 요소는 KnockoutStatic 인터페이스로 확장됩니다. 내가 <reference ... />namespace 모듈을 사용하여 거대한 TS 응용 프로그램을 기반으로 마이 그 레이션하는 중이 야. 이전에는 확장 인터페이스 을 어디서나 쉽게으로 선언하고 선언이 병합되었습니다. 내 확장 프로그램이 이렇게 생겼다고 가정 해 봅시다.

interface KnockoutStatic { 
    doSomething(): void; 
} 

내가 이런 식으로 선언 한 파일 KnockoutExtensions.d.ts을 만들려고했습니다.

import "knockout"; 

declare module "knockout" { 
    export interface KnockoutStatic { 
    doSomething(): void; 
    } 
} 

하지만 어딘가에 모두 knockout 내 확장을 가져올 때, TS는 여전히 doSomething 전화를 확인할 수 없습니다. 타이프 2.0 새로운 d.ts 서브 시스템을 사용하여 라이브러리 인터페이스를 확장하는 적절한 방법은

import * as ko from "knockout"; 
import "./KnockoutExtensions"; 

ko.doSomething(); // error 

무엇인가?

TypeScript 2.0이 설치된 Visual Studio 2015 업데이트 3을 사용하고 있습니다.

답변

0

모듈 외부에서 인터페이스를 만들어야합니다. 은 아니며을 내보내기와 함께 선언하십시오.

interface KnockoutStatic { doSomething(): void; }

module example { //...do stuff }

당신은 당신의 파일을, 당신이 당신의 인터페이스 확장을 추가 할 경우 깨끗하게 유지 할 수 있습니다.

+0

이것은 작동하지 않았습니다.이 모듈은 모듈을 사용하지 않았을 때만 작동하지만 순수한 네임 스페이스입니다. –

0

문제는 knockout 타이핑 파일이 export = 구문을 사용하며 "향상된 기능 향상"이 아닙니다. 참조 용으로 this을 참조하십시오.

나를위한 가장 간단한 해결책은 declare global { }에있는 확장을 랩핑하여 knockout으로 입력 파일이 전체 범위의 모든 것을 선언하는 것이 었습니다.

declare global { 
    interface KnockoutStatic { 
    doSomething(): void; 
    } 
} 
0

'knockout'또는 다른 TypeScript 네임 스페이스를 쉽게 확장 할 수 있습니다.

예 : 생성 녹아웃 - extension.d.ts는

/// <reference path="<path-to-typings-dir>/knockout/index.d.ts" /> 

declare module 'knockout' { 

    export interface CustomType { 

    customField: string; 

    customMethod(arg1: number, arg2: boolean): boolean; 
    } 

    namespace customNamespace { 

    export interface AnotherCustomType { 
     customField1: string; 
     customField2: boolean; 
    } 
    } 

    // NOTE: extending existing interface 
    export interface KnockoutStatic { 
    customMethod(): void; 
    } 
} 

참고 파일 : 타이프 스크립트 컴파일러에 의해이 파일이 있는지 픽업을 보장합니다.

확장 모듈의 새로 정의 된 유형을 사용하십시오.이상의 모듈 및 ModulesNamespaces에 타이프 라이터 문서를 확인할 수 있습니다 네임 스페이스에 대한 정보와 그 together을 사용하기 위해

// one way 
import { CustomType } from 'knockout'; 

const foo: CustomType; 

// second way 
import * as kc from 'knockout'; 

const foo: kc.CustomType; 
const bar: kc.customNamespace.AnotherCustomType; 

.

건배!