gpt4 book ai didi

javascript - 如何在 typescript 中导入/使用 Reflect

转载 作者:数据小太阳 更新时间:2023-10-29 05:40:28 26 4
gpt4 key购买 nike

我正在尝试使用 this SO answer 中的代码.它使用反射。这是一个副本:

export function CustomComponent(annotation: any) {
return function (target: Function) {
var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);

var parentAnnotation = parentAnnotations[0];
Object.keys(parentAnnotation).forEach(key => {
if (isPresent(parentAnnotation[key])) {
annotation[key] = parentAnnotation[key];
}
});
var metadata = new ComponentMetadata(annotation);

Reflect.defineMetadata('annotations', [ metadata ], target);
}
}

首先,我得到了这两个错误:

Property 'getMetadata' does not exist on type 'typeof Reflect'.
Property 'defineMetadata' does not exist on type 'typeof Reflect'.

然后我运行了npm install reflect-metadata,但我不知道如何使用它。

import { Reflect } from reflect-metadata;

Module '".../node_modules/reflect-metadata/index"' has no exported
member 'Reflect'.

或者

import { Reflect } from 'reflect-metadata/Reflect';

Cannot find name 'Record'.
Type '{}' is not assignable to type 'V'.
File '.../node_modules/reflect-metadata/Reflect.ts' is not a module.

或者

import "reflect-metadata"

rollup: Treating 'fs' as external dependency
bundle update failed: Error transforming .../node_modules/typescript/lib/typescript.js
with 'commonjs' plugin: The keyword 'package' is reserved (57066:28) in
.../node_modules/typescript/lib/typescript.js

或者

var reflect = require("reflect-metadata");

Cannot find name 'require'.

或者

declare var require: any;
var reflect = require("reflect-metadata");
var Reflect = reflect.Reflect;

rollup: Treating 'fs' as external dependency
bundle update failed: Error transforming .../node_modules/typescript/lib/typescript.js
with 'commonjs' plugin: The keyword 'package' is reserved (57066:28) in
.../node_modules/typescript/lib/typescript.js

当然,我只是遗漏了一些愚蠢的东西,甚至是错字。我可以做什么来使用此代码?

最佳答案

您必须将类型声明与 (js) 库一起导入

npm install reflect-metadata -D

在您的 .ts 文件中:

 import "reflect-metadata";

关于javascript - 如何在 typescript 中导入/使用 Reflect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41270800/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com