網站搜尋

typescript - Reflection metadata 'design:paramtypes' 在 Deno 上返回未定義


我正在嘗試在 TypeScript 中使用 Deno 實作依賴注入,然而,我遇到了一個問題,Reflect.getMetadata('design:paramtypes', ...) 返回了 undefined 的值,我不明白為什麼會這樣。

Deno 1.6.0
Ubuntu 18.04.5 LTS

我正在使用這個檔案作為 Reflect:https://github.com/edualb/dependencyInjectionPOC/blob/main/Reflect.ts

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "lib": ["es5", "es6", "dom"],
  }
}

程式碼

decorator.ts
export interface Type<T> {
    new(...args: any[]): T;
}

export function Injectable(): (target: Type<any>) => void {
    return (target: Type<any>) => {}
}
service2.ts
import { Injectable } from './decorator.ts';

@Injectable()
export class Service2 {
    constructor() {}
}
service.ts
import { Injectable } from './decorator.ts';
import { Service2 } from './service2.ts';

@Injectable()
export class Service {
    constructor(private s2: Service2) {}
}
main.ts
import { Reflect } from './Reflect.ts';
import { Service } from './service.ts';

console.log(Reflect.getMetadata('design:paramtypes', Service)) // here is returning undefined

用於執行的命令:

deno run main.ts

Github: https://github.com/edualb/dependencyInjectionPOC

有人可以幫忙處理這個問題嗎?

答案#1

請參見 https://deno.land/[email /advanced/typescript/configuration :

建議使用 deno.json 而不是 tsconfig.json …

deno.json 的一個最小範例:

{    
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "jsx": "react-jsx",
    "jsxImportSource": "preact"
  }
}

那麼像 Reflect.getMetadata("design:type", target, key); 之類的東西就可以運作了。

答案#2

我已經透過在執行命令中加入標誌 -c/--config 解決了這個問題:

deno run -c tsconfig.json main.ts