error TS2339: Property 'x' does not exist on type 'Y'

前端 未结 6 1212
忘掉有多难
忘掉有多难 2020-12-01 12:02

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):



        
6条回答
  •  无人及你
    2020-12-01 12:28

    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.


    Edit

    You can have a helper class for map instances, something like:

    class Map {
        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 {
        return images.get("main");
    }
    

    I have something like that implemented, and I find it very useful.

提交回复
热议问题