获取本地 JSON 数据:元素隐式具有类型 "any"
Get local JSON data: The element has a type "any" implicitly
我在 Node JS 中有一个带有 Typescript 的项目,我在其中创建一个 API 以根据给定变量从本地 JSON 文件获取数据。
这是我的 model.ts
:
interface ListProductBatchModel {
resp: ResultMsg
}
interface ResultMsg {
name?: string,
price?: string,
error?: string
}
export { ListProductBatchModel, ResultMsg };
这是我的 properties
JSON 文件:
{
"CT": {
"name": "box",
"price": "5,00"
},
"CC": {
"name": "car",
"price": "6,00"
}
}
这是我的 controller.ts
:
import * as logger from 'winston';
import { Controller, Get, Response, Route, SuccessResponse, Tags } from 'tsoa';
import { ListProductBatchModel } from './models/listProduct.models';
import { ListProductBatchUtils } from './utils/listProductBatch.utils';
@Route('/list/product')
@Tags('list-product')
export class ListProductBatchController {
private listProductBatchUtils: ListProductBatchUtils;
constructor() {
this.listProductBatchUtils = new ListProductBatchUtils();
}
@Get('/{codProduct}')
@SuccessResponse(200, 'Success Response')
async listProductBatch(codProduct: string): Promise<ListProductBatchModel> {
try {
const listProductBatch = await this.listProductBatchUtils.getDataProduct(codProduct);
return Promise.resolve(listProductBatch as ListProductBatchModel);
} catch (error) {
logger.info(JSON.stringify(error));
return Promise.reject(error);
}
}
}
这是我的 utils.ts
:
import * as logger from 'winston';
import * as getProperty from '../json/product.json';
import { ListProductBatchModel, ResultMsg } from '../models/listProduct.models';
export class ListProductBatchUtils {
public async getDataProduct(codProduct: string): Promise<ListProductBatchModel> {
try {
let result: ResultMsg;
if (getProperty[codProduct.toUpperCase()]) {
result = {
name: getProperty[codProduct.toUpperCase()].name,
price: getProperty[codProduct.toUpperCase()].price
}
}else {
result = {
error: "ERROR"
}
}
logger.info('start')
return Promise.resolve({ resp: result });
} catch (error) {
logger.info(JSON.stringify(error));
return Promise.reject(error);
}
}
}
这是我在 getProperty [codProduct.toUpperCase ()]
中得到的错误:
The element has a type "any" implicitly because the expression of type "string" cannot be used to index the type "{CT: {name: string; price: string;}; CC: {name: string; price : string;};} ".
No index signature was found with a parameter of type "string" in type "{CT: {name: string; price: string;}; CC: {name: string; price: string;};}".
我的问题:我不明白这个错误是怎么产生的,我想要的是取与codProduct变量匹配的name和price属性。为什么会发生这种情况?我做错了什么,我该如何解决?
现在,codProduct
是 string
。当您通过其下标 []
访问 getProduct
时,TypeScript 希望您使用 getProduct
的索引(在本例中为 "CT"
或 "CC"
).
您可以通过将 string
转换为 keyof
getProperty
的类型来满足 TypeScript 编译器的要求。请注意,这将在编译时起作用,但 不会 保证它 在运行时实际上是 getProperty
的键。但是,由于您已经在进行布尔检查,所以在您的情况下似乎没问题。
这是一个简化的例子:
const getProperty = {
"CT": {
"name": "box",
"price": "5,00"
},
"CC": {
"name": "car",
"price": "6,00"
}
};
type GetPropertyType = typeof getProperty;
function myFunc(input: string) {
const result = getProperty[input.toUpperCase() as keyof GetPropertyType].name;
}
我在 Node JS 中有一个带有 Typescript 的项目,我在其中创建一个 API 以根据给定变量从本地 JSON 文件获取数据。
这是我的 model.ts
:
interface ListProductBatchModel {
resp: ResultMsg
}
interface ResultMsg {
name?: string,
price?: string,
error?: string
}
export { ListProductBatchModel, ResultMsg };
这是我的 properties
JSON 文件:
{
"CT": {
"name": "box",
"price": "5,00"
},
"CC": {
"name": "car",
"price": "6,00"
}
}
这是我的 controller.ts
:
import * as logger from 'winston';
import { Controller, Get, Response, Route, SuccessResponse, Tags } from 'tsoa';
import { ListProductBatchModel } from './models/listProduct.models';
import { ListProductBatchUtils } from './utils/listProductBatch.utils';
@Route('/list/product')
@Tags('list-product')
export class ListProductBatchController {
private listProductBatchUtils: ListProductBatchUtils;
constructor() {
this.listProductBatchUtils = new ListProductBatchUtils();
}
@Get('/{codProduct}')
@SuccessResponse(200, 'Success Response')
async listProductBatch(codProduct: string): Promise<ListProductBatchModel> {
try {
const listProductBatch = await this.listProductBatchUtils.getDataProduct(codProduct);
return Promise.resolve(listProductBatch as ListProductBatchModel);
} catch (error) {
logger.info(JSON.stringify(error));
return Promise.reject(error);
}
}
}
这是我的 utils.ts
:
import * as logger from 'winston';
import * as getProperty from '../json/product.json';
import { ListProductBatchModel, ResultMsg } from '../models/listProduct.models';
export class ListProductBatchUtils {
public async getDataProduct(codProduct: string): Promise<ListProductBatchModel> {
try {
let result: ResultMsg;
if (getProperty[codProduct.toUpperCase()]) {
result = {
name: getProperty[codProduct.toUpperCase()].name,
price: getProperty[codProduct.toUpperCase()].price
}
}else {
result = {
error: "ERROR"
}
}
logger.info('start')
return Promise.resolve({ resp: result });
} catch (error) {
logger.info(JSON.stringify(error));
return Promise.reject(error);
}
}
}
这是我在 getProperty [codProduct.toUpperCase ()]
中得到的错误:
The element has a type "any" implicitly because the expression of type "string" cannot be used to index the type "{CT: {name: string; price: string;}; CC: {name: string; price : string;};} ".
No index signature was found with a parameter of type "string" in type "{CT: {name: string; price: string;}; CC: {name: string; price: string;};}".
我的问题:我不明白这个错误是怎么产生的,我想要的是取与codProduct变量匹配的name和price属性。为什么会发生这种情况?我做错了什么,我该如何解决?
现在,codProduct
是 string
。当您通过其下标 []
访问 getProduct
时,TypeScript 希望您使用 getProduct
的索引(在本例中为 "CT"
或 "CC"
).
您可以通过将 string
转换为 keyof
getProperty
的类型来满足 TypeScript 编译器的要求。请注意,这将在编译时起作用,但 不会 保证它 在运行时实际上是 getProperty
的键。但是,由于您已经在进行布尔检查,所以在您的情况下似乎没问题。
这是一个简化的例子:
const getProperty = {
"CT": {
"name": "box",
"price": "5,00"
},
"CC": {
"name": "car",
"price": "6,00"
}
};
type GetPropertyType = typeof getProperty;
function myFunc(input: string) {
const result = getProperty[input.toUpperCase() as keyof GetPropertyType].name;
}