Quiero crear un tipo para una matriz de objetos. La matriz de objetos puede verse así:
const troll = [ { a: 'something', b: 'something else' }, { a: 'something', b: 'something else' } ];el tipo que estoy tratando de usar es:
export type trollType = [{ [key: string]: string }];Entonces quiero usar el tipo como este:
const troll: trollType = [ { a: 'something', b: 'something else' }, { a: 'something', b: 'something else' } ];pero me sale este error:
Type '[{ a: string; b: string; }, { a: string; b: string; }]' is not assignable to type 'trollType'. Source has 2 element(s) but target allows only 1Puedo hacer algo como esto:
export type trollType = [{ [key: string]: string }, { [key: string]: string }];pero digamos que mi matriz de objetos tendrá 100 objetos en la matriz.
Al establecer un tipo para una matriz, debe tener este formato any[] .
Entonces en tu caso
export type trollType = { [key: string]: string }[];Puede intentar usar el tipo de Record para almacenar las definiciones de atributos del objeto y crear una matriz a partir de él, como se muestra a continuación:
type TrollType = Record<string, string>[]; const troll: TrollType = [ { a: 'something', b: 'something else' }, { a: 'something', b: 'something else' } ];