Tengo esta interfaz en la que básicamente quiero tener una matriz de hashes. Algo como esto (probablemente no es correcto):
export interface EntitySpec { originId: EntityType; mandatoryProperties: Array<{ [key: string]: string }>; }Pero quiero aplicar la interfaz de esta manera:
const spec: EntitySpec = { originId: 1, mandatoryProperties: { 'code': 'sad', 'name': 'this', 'comment': 'here', }, };Pero obtengo esto: escriba '{ código: cadena; }' no se puede asignar al tipo '{ [clave: cadena]: cadena; }[]'. ¿Cómo haría esto correctamente?
Es porque mandatoryProperties son una Array de objetos. Envuélvalo en [] y debería estar bien:
const spec: EntitySpec = { originId: 1, mandatoryProperties: [ { 'code': 'sad', 'name': 'this', 'comment': 'here', } ] };Si desea asignar un object a mandatoryProperties , elimine Array<> de una interfaz de la siguiente manera:
export interface EntitySpec { originId: EntityType; mandatoryProperties: { [key: string]: string }; } const spec: EntitySpec = { originId: 1, mandatoryProperties: { 'code': 'sad', 'name': 'this', 'comment': 'here', }, }; de lo contrario, ajuste las propiedades mandatoryProperties dentro de una matriz de la siguiente manera:
export interface EntitySpec { originId: EntityType; mandatoryProperties: Array<{ [key: string]: string }>; } const spec: EntitySpec = { originId: 1, mandatoryProperties: [{ 'code': 'sad', 'name': 'this', 'comment': 'here', }], };Sus mandatoryProperties son un objeto, no una matriz. Necesitas eliminar ese Array<>
export interface EntitySpec { originId: EntityType; mandatoryProperties: { [key: string]: string }; } Sin embargo, si necesita una matriz, puede agregar [] al final:
export interface EntitySpec { originId: EntityType; mandatoryProperties: { [key: string]: string }[]; } const spec: EntitySpec = { originId: 1, mandatoryProperties: [ { 'code': 'sad', 'name': 'this', 'comment': 'here', } ] };