The issue with type checking being disrupted when importing from a TypeScript file

I have a TypeScript file containing an openapi object schema constant:

export default {
  "title": "Draft",
  "description": "A new draft listing",
  "type": "object",
  "additionalProperties": false,
  "required": [
    "id"
  ],
  "properties": {
    "id": {
      "type": "string"
    }
  }
}

Now, I'm attempting to include this schema as a component in the general OpenAPI schema in another file:

import Draft from './__generated_schemas__/draft.js'

import { OpenAPIV3 } from 'openapi-types'

export const schema: OpenAPIV3.Document = {
  openapi: '3.1',
  info: {
    title: 'Properties API',
    version: '1.0.0',
    description:
      'Nice service description'
  },
  components: {
    schemas: {
      Draft
    }
  },
  paths: {}
}

However, TypeScript throws an error when I do this:

 packages/api/src/schema.ts(22,7): error TS2322: Type '{ title: string; description: string; type: string; additionalProperties: boolean; required: string[]; properties: { id: { type: string; }; }; }' is not assignable to type 'ReferenceObject | SchemaObject'.
   Type '{ title: string; description: string; type: string; additionalProperties: boolean; required: string[]; properties: { id: { type: string; }; }; }' is not assignable to type 'NonArraySchemaObject'.
     Types of property 'type' are incompatible.
       Type 'string' is not assignable to type 'NonArraySchemaObjectType | undefined'.

Interestingly, if I manually insert the JSON from the TypeScript file into the OpenAPI schema, everything works fine:

export const schema: OpenAPIV3.Document = {
  openapi: '3.1',
  info: {
    title: 'Properties API',
    version: '1.0.0',
    description:
      'Nice service description'
  },
  components: {
    schemas: {
      Draft: {
        "title": "Draft",
        "description": "A new draft listing",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id"
        ],
        "properties": {
          "id": {
            "type": "string"
          }
        }
      }
    }
  }

Any insight on why TypeScript type checking fails in the former case? The object schema and overall OpenAPI schema seem correct to me...

Answer №1

In my opinion, the crucial information lies within the final line:

The 'string' type cannot be assigned to the 'NonArraySchemaObjectType | undefined' type.

Although I am not entirely certain about what exactly the NonArraySchemaObjectType represents, you would need to refer to the typings for a clear understanding. My speculation is that it comprises a union type of various constant strings like: 'number' | 'string' | 'boolean'.

When utilizing a separate file devoid of any typings, typescript will make assumptions concerning each type.

For instance, if you input:

export default {
  "title": "Draft",
  "description": "A new draft listing",
  "type": "object",
  ...
}

This will yield a typing similar to:

{ 
  title: string, 
  description: string, 
  type: string, 
  ...
}

However, simply having type as a regular string is not sufficient; you want it to be of a specific type: NonArraySchemaObjectType. Due to the absence of any typing clues, typescript perceives this as identical to title or description.

The reason why it functions in the same file is because you specify at object creation: OpenAPIV3.Document.

Please consider reviewing the following example:

let aString = "a"; // type is string
let aType = "a" as const; // type is "a"

type unionType = "a" | "b";

const ex1: { value: unionType } = {
    value: aType // ok, since "a" fits in "a" | "b"
};

const ex2: { value: unionType } = {
    value: "a" // ok, since typescript interprets that the "a" you typed here could be of type unionType
};

const ex3: { value: unionType } = {
    value: aString // Error, because you're assigning a string, which could be something else than "a" or "b"
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In TypeScript Next.js 14 APP, object literals are limited to declaring existing properties

I encountered an error in my typescript next.js 14 APP. I need assistance resolving this issue, which states: Object literal may only specify known properties, and 'productPackages' does not exist in type '(Without<ProductCreateInput, Pr ...

Having trouble updating properties of child components in Angular

I have a data filtering functionality where I enter values in a filter popup and successfully retrieve results. I then store this data in local storage to retain it when navigating back from another page. However, upon returning to the filter component, I ...

Identifying the End of an HTML Video in Angular 2

Seeking assistance with detecting the end of an HTML video in Ionic2 (Angular2 and Typescript). The relevant code snippets can be found below: Template: <video poster="" id="v" playsinline autoplay webkit-playsinline onended="vidEnded()"> <s ...

Importing Typescript modules by specifying their namespace instead of using a function

I have been working on a project where I needed to generate typings from graphql using the gql2ts library. In the gql-2-ts file, I initially used a namespace import for glob, which resulted in TypeScript showing me an error as intended. I then switched the ...

How can I convert the >= value into an ASCII character within a TypeScript file?

Within my Angular TS file, I am attempting to identify if a string contains the characters >= and then substitute them with the corresponding ASCII character for greater than or equal to. Here is my current code snippet: @Input() public set textLabel(va ...

Creating a new item in Angular 2 using user input

Just dipping my toes into Angular2 and attempting to append a new item to the list through input. However, upon clicking submit, instead of text I get [object Object]. Check out the code snippet below: app.component.html <form (submit)="addItem(item) ...

The type of a reference variable in a type definition of another variable

Can we reference the type of one variable (let's call it someVar) in TypeScript when declaring the type of another variable (anotherVar)? For example, instead of creating a separate type declaration for { complex: 'type' }, can we directly ...

Concealing applicationId and clientToken in Datadog

I'm currently using an Angular application and I've integrated it with the Datadog application to utilize Session and Replay (RUM). However, I am concerned about the security of my sensitive information such as applicationId and clientToken. Is t ...

The parameter of type 'void' cannot be assigned to the parameter of type 'PathParams'

Established the route handler and encountered an issue while integrating it into my route. import {Application, NextFunction} from 'express'; import {container} from 'tsyringe'; const routeConstantsArray = { }; const constants: any ...

Unlock the power of Env variables on both server and client components with Next.js! Learn how to seamlessly integrate these

In my Next.js app directory, I am facing the need to send emails using Nodemailer, which requires server-side components due to restrictions on client-side sending. Additionally, I am utilizing TypeScript in this project and encountering challenges when tr ...

Analyzing memory consumption by an individual function in a Node.js environment

Our current experiment involves measuring the memory usage of specific functions. Initially, we attempted to utilize process.memoryUsage().heapUsed before and after calling the function, but encountered issues due to the behavior of the garbage collector. ...

When using primeng, it is necessary to place the hyphen on the parent node when selecting a child element

https://i.sstatic.net/KM8Fo.png This code is written in Typescript. //DECLARATIONS AND CODE Ngonint--> ngOnInit() { if(this.title === "Create"){ this.dataProfilo = {} this.dataProfilo.function = []; this.ser ...

``There seems to be an issue with retrieving and displaying data in Ionic2 when using nav

I am facing an issue with displaying the data received from NavParams. I have used console.log() to confirm that I am getting the correct data, but for some reason, I am unable to display it on the new page. I suspect that there might be an error in how I ...

Ways to stop dialog from disappearing in Reactjs

This code snippet demonstrates the implementation of a popup with buttons, where clicking the cancel button triggers a confirmation dialog. To make the popup disappear when clicked outside of it, the following event handling is employed: const popupRef = ...

Error is being thrown due to defining a variable after it has already been declared and

Before I use a variable, I encountered the issue of using it before its definition, interface IProps extends WithStyles<typeof STYLES>; const STYLES = () => ({ }) Although it didn't cause any errors, a warning appeared: STYLES used befo ...

React: Issue with input values not correctly updating across multiple fields when changing state toggles

I am working on a React component that needs to update input values for multiple players independently. However, I am facing an issue where toggling a state causes the first input's value to incorrectly propagate to all other inputs. Additionally, cle ...

Error encountered in Typescript when attempting to invoke axios - the call lacks a suitable overload

When I make a call to axios, I include a config object like this: const req = { method, url, timeout: 300000, headers: { 'Content-Type': 'application/json' } } axios(req) An error in TypeScript is thrown stating that "No overload matc ...

Exploring TypeScript: Understanding how to define Object types with variable properties names

Having an issue with a React + TypeScript challenge that isn't causing my app to crash, but I still want to resolve this lingering doubt! It's more of a query than a problem! My goal is to set the property names of an object dynamically using va ...

Why is the useContext array appearing empty when accessed in a function within the same context, despite being pre-populated?

I am encountering an issue with my useContext setup, where I provide all logged-in users. When the app runs initially or when users log in, the array is populated with all current users on the server, which works as intended. However, when the "user-connec ...

Refresh Ionic 2 Platform

I'm currently working on an Ionic 2 app and whenever I make a change to the .ts code, I find myself having to go through a tedious process. This involves removing the platform, adding the Android platform again, and then running the app in Android or ...