Búsqueda de sitios web

typescript - Permitir que la interfaz se convierta implícitamente a JsonData


¿Puedo modificar esta definición de un tipo de datos Json para permitir que los tipos compatibles con JSON se conviertan implícitamente a él?

type JsonValue =
    | string
    | number
    | boolean
    | null
    | { [property: string]: JsonValue }
    | JsonValue[];

Tengo un tipo como el siguiente:

interface AttachedFile {
  id: string
  name: string
  size: number
  type: string
}

Y quiero una tarea para trabajar:

const q : JsonValue = someAttachedFile

Pero obtengo el error Type 'AttachedFile' no se puede asignar al tipo '{ [property: string]: JsonValue; }'. Falta la firma de índice en el tipo 'AttachedFile'.

Respuesta #1

JsonValue no es un JSON

type JsonValue =
    | string
    | number
    | boolean
    | null
    | { [property: string]: Json }
    | Json[];

interface JSON {
    readonly [Symbol.toStringTag]: string;
}

Tu tipo es objeto de JavaScript

interface AttachedFile {
  id: string
  name: string
  size: number
  type: string
}

Para hacer JSON, necesitas llamar,

const q = JSON.stringify(someAttachedFile)

Lo que resultará en un ¡String!

"{                       // now this is JsonValue
  id: "some id" // <------------------||||
  name: "some name" // <---------------|||
  size: 1 // <--------------------------||
  type: "some type" // <-----------------|
}"

Entonces JsonValue nunca es usado por el desarrollador, lo usa Visual Studio Code para ayudar a trabajar con archivos JSON (por ejemplo, cuando haces require('data.json'))

Y el documento de TypeScript usa JsonValue para demostrar tipos recursivos, lo cual es fácil de entender con JSON

Todo lo que puedes hacer es convertir el objeto json a tu ArchivoAdjunto

const q: AttachedFile = JSON.parse(someJsonString) // convert json string to AttachedFile