No se puede hacer que TypeScript importe JSON con los tipos correctos
Tengo el siguiente archivo test.json que deseo importar en una forma tipada.
{
"items": [
{
"kind": "youtube#video",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/WnVAkK876rA/default.jpg",
"width": 120,
"height": 90
}
}
},
{
"kind": "youtube#video",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/jhTpc7nFtfI/default.jpg",
"width": 120,
"height": 90
},
"maxres": {
"url": "https://i.ytimg.com/vi/jhTpc7nFtfI/maxresdefault.jpg",
"width": 1280,
"height": 720
}
}
}
]
}
Este es mi App.tsx:
import { TestData } from './Types';
import * as testData from './test.json'
const ttt: TestData = testData;
Este es Types.ts
export interface TestData {
items: TestDataPiece[]
}
export interface TestDataPiece {
kind: string,
thumbnails: {[key: string]: {
url: string,
width: number,
height: number
}}
}
En mi tsconfig.json uso "resolveJsonModule": true. Sin embargo, obtengo este error:
[tsl] ERROR in C:\Users\home\IdeaProjects\yt-glasat\src\App.tsx(11,7)
TS2322: Type '{ items: ({ kind: string; thumbnails: { default: { url: string; width: number; height: number; }; maxres?: undefined; }; } | { kind: string; thumbnails: { default: { url: string; width: number; height: number; }; maxres: { ...; }; }; })[]; }' is not assignable to type 'TestData'.
Types of property 'items' are incompatible.
Type '({ kind: string; thumbnails: { default: { url: string; width: number; height: number; }; maxres?: undefined; }; } | { kind: string; thumbnails: { default: { url: string; width: number; height: number; }; maxres: { ...; }; }; })[]' is not assignable to type 'TestDataPiece[]'.
Type '{ kind: string; thumbnails: { default: { url: string; width: number; height: number; }; maxres?: undefined; }; } | { kind: string; thumbnails: { default: { url: string; width: number; height: number; }; maxres: { ...; }; }; }' is not assignable to type 'TestDataPiece'.
Type '{ kind: string; thumbnails: { default: { url: string; width: number; height: number; }; maxres?: undefined; }; }' is not assignable to type 'TestDataPiece'.
Types of property 'thumbnails' are incompatible.
Type '{ default: { url: string; width: number; height: number; }; maxres?: undefined; }' is not assignable to type '{ [key: string]: { url: string; width: number; height: number; }; }'.
Property '"maxres"' is incompatible with index signature.
Type 'undefined' is not assignable to type '{ url: string; width: number; height: number; }'.
Respuesta #1
El problema es que el tipo inferido de los datos tiene una propiedad maxres que es opcional, lo que significa que su tipo es {url: string; width: number; height: number} | undefined. Pero el tipo de tu objeto de miniatura no permite undefined para los valores del objeto con la firma de índice.
Cualquiera de estos haría que el error desapareciera:
- Asegúrese de que todos los objetos relevantes en el JSON tengan una propiedad
maxres; o - Permitir
undefineden objetos de miniatura; o - Usa una afirmación de tipo al hacer la asignación, quizás respaldada por una verificación en tiempo de ejecución
Supongo que no puedes hacer el #1 y no quieres hacer el #2, así que te queda la aserción de tipo:
const ttt = testData as TestData;
Las aserciones de tipo generalmente son una solución de último recurso; sin embargo, puedes respaldarlas con una verificación en tiempo de ejecución para hacer la validación en testData y asegurarte de que encaje en la interfaz utilizando una función de guarda de tipos o una función de aserción de tipos.
Por ejemplo:
function assertIsValidTestData(data: any): asserts data is TestData {
if (!Array.isArray(data) ||
data.some(element => {
return typeof element !== "object" ||
typeof element.kind !== "string" ||
typeof element.thumbnails !== "object" ||
Object.values(element.thumbnails).some(thumbnail => {
return typeof thumbnail !== "object" ||
typeof thumbnail.url !== "string" ||
typeof thumbnail.width !== "number" ||
typeof thumbnail.height !== "number";
})
})) {
throw new Error(`Test data is not valid`);
}
}
Y luego
assertIsValidTestData(testData);
const ttt: TestData = testData;
Respuesta #2
Usar una aserción de tipo debería funcionar en tu caso:
const ttt = testData as TestData;
