Search code examples
javascripttypescript

How to interpret brackets surrounding a Interface string Property That Maps to an Object Type Literal?


I'm trying to understand what the corresponding javascript object is that would fit the type definition given for [propertyName: string]:.... If you click the link it shows the entire definition.

Also how should we interpret the brackets around [propertyName: string]:...?


Solution

  • It's an index signature that says the object can contain any fields with any name, but values of all fields must be of the type specified after :

    Let's consider a simplified example :

    interface Indexable {
        [properyName: string]: {
            isValid: boolean
        }
    }
    
    let valid: Indexable = {
        anyName: { isValid: true }, 
        anyOtherName : { isValid: false }
    };
    
    let invalid: Indexable = {
        invalidFields: { isValid_: true }, // no isValid field 
        excessFields: { isValid: true, unexpectedProp: 0 }, // Object literal may only specify known properties
    };
    let invalidType: Indexable = {
        numberField: 0  // 'numberField' is incompatible with index signature.
    };