javascripttypescripterror-handlinginterface

typescipt index property in interface


interface IErrorContainer {
id: number;
[prop: string] : string; }


const errorBag1: IErrorContainer = {
id: 1,
email: "Not valid email",
userName: "length must be upper then 8" }

when I add 'id' to IErrorContainer, I got an assinging error, why did I get?


Solution

  • [prop:string] makes every key on IErrorContainer have to be a string. so by saying id:number you're going against your own rule and saying that a key of IErrorContainer can be a number. One way to solve it is to remove the id key completely and add |number to your interface like so:

    interface IErrorContainer {
    
    [prop: string]: string|number
    
    }
    

    You basically can't have any keys and type checked keys in the same interface.