prosource

유형 스크립트 확장 서드 파티 선언 파일

probook 2023. 7. 2. 20:50
반응형

유형 스크립트 확장 서드 파티 선언 파일

타사 선언 파일을 확장하려면 어떻게 해야 합니까?
예를 들어, 나는 확장하고 싶습니다.Context@types/koa에서 필드를 추가합니다(resource) 그것으로.
시도해 봤습니다.

// global.d.ts
declare namespace koa {
    interface Context {
        resource: any;
    }
}

하지만 효과가 없습니다.

error TS2339: Property 'resource' does not exist on type 'Context'.

갱신하다

다음 오류가 발생하는 내 코드의 단순화된 버전:

import {Context} from 'koa';
import User from './Models/User';
class Controller {
   async list(ctx: Context) {
        ctx.resources = await User.findAndCountAll();
        ctx.body = ctx.resources.rows;
        ctx.set('X-Total-Count', ctx.resources.count.toString());
        ctx.status = 200;
    }
}

typescript v2.4

// tsconfig.json
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "exclude": [
    "node_modules"
  ]
}

여기에 설명된 대로 모듈 확대를 사용해야 합니다.

import { Context } from "koa";

declare module "koa" {
    interface Context {
        resource: any;
    }
}

언급URL : https://stackoverflow.com/questions/46493253/typescript-extend-third-party-declaration-files

반응형