Home > Net >  typescipt index propery in interface
typescipt index propery in interface

Time:08-17

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?

CodePudding user response:

[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.

  • Related