错误 TS2339:类型“Y"上不存在属性“x" [英] error TS2339: Property 'x' does not exist on type 'Y'
问题描述
我不明白为什么这段代码会产生 TypeScript 错误.(不是原代码,有点派生,请忽略例子中的废话):
I don't understand why this code generates TypeScript error. (It's not the original code and is a bit derived, so please ignore the non-sense in the example):
interface Images {
[key:string]: string;
}
function getMainImageUrl(images: Images): string {
return images.main;
}
我收到错误(使用 TypeScript 1.7.5):
I'm getting error (using TypeScript 1.7.5):
错误 TS2339:图像"类型上不存在属性main".
error TS2339: Property 'main' does not exist on type 'Images'.
当然我可以在写作时摆脱错误:
Of course I could get rid of the error when writing:
return images["main"];
我不希望使用字符串来访问该属性.我能做什么?
I'd prefer not using string to access the property. What can I do?
推荐答案
如果您希望能够访问 images.main
那么您必须明确定义它:
If you want to be able to access images.main
then you must define it explicitly:
interface Images {
main: string;
[key:string]: string;
}
function getMainImageUrl(images: Images): string {
return images.main;
}
您无法使用点表示法访问索引属性,因为打字稿无法知道对象是否具有该属性.
但是,当您专门定义一个属性时,编译器就会知道它是否存在(或不存在),它是否可选以及类型是什么.
You can not access indexed properties using the dot notation because typescript has no way of knowing whether or not the object has that property.
However, when you specifically define a property then the compiler knows that it's there (or not), whether it's optional or not and what's the type.
你可以有一个地图实例的辅助类,比如:
You can have a helper class for map instances, something like:
class Map<T> {
private items: { [key: string]: T };
public constructor() {
this.items = Object.create(null);
}
public set(key: string, value: T): void {
this.items[key] = value;
}
public get(key: string): T {
return this.items[key];
}
public remove(key: string): T {
let value = this.get(key);
delete this.items[key];
return value;
}
}
function getMainImageUrl(images: Map<string>): string {
return images.get("main");
}
我实现了类似的东西,我发现它非常有用.
I have something like that implemented, and I find it very useful.
这篇关于错误 TS2339:类型“Y"上不存在属性“x"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!