Establish a default value for a TypeScript generic Type: distinguishing between 'unknown' and 'any'

An interface has been created with a parameter that takes a generic type input named Data

export interface MyStructure<Data> {
  id: string;
  data: Data;
}

The goal is to allow the Data type to be optional in order to support scenarios like:

function printId(obj: MyStructure): void {
    console.log(obj.id);
}

In certain contexts like printId, specifying the generic type for MyStructure<Data> is not necessary.

The question arises on how to handle this situation: should the default be set to any or unknown, and what are the implications.

export interface MyStructure<Data = unknown> {
  id: string;
  data: Data;
}
export interface MyStructure<Data = any> {
  id: string;
  data: Data;
}

Answer №1

When deciding between using Data = unknown and Data = any, it's important to consider the following distinctions:

  • unknown: Offers enhanced type safety by limiting the operations that can be performed on the data property unless its type is explicitly checked first, reducing the risk of misuse

  • any: Permits virtually any type of operation on the data property, potentially leading to unexpected runtime errors.

Overall, opting for unknown would be the preferable choice.

export interface MyStructure<Data = unknown> {
  id: string;
  data: Data;
}

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

What exactly defines the nature of a type?

Have you ever wondered about the nature of a type? All this talk may seem perplexing, but sometimes code speaks louder than words. // Consider an interface interface A { } // Now, imagine a class that implements this interface. // There are several impl ...

What is the recommended way to use the async pipe to consume a single Observable property in a view from an Angular2

Suppose I have a component with the following property: import { Component, OnInit } from 'angular2/core'; import { CarService } from 'someservice'; @Component({ selector: 'car-detail', templateUrl: './app/cars/ ...

Issue with migrating TypeOrm due to raw SQL statement

Is it possible to use a regular INSERT INTO statement with TypeOrm? I've tried various ways of formatting the string and quotes, but I'm running out of patience. await queryRunner.query('INSERT INTO "table"(column1,column2) VALUES ...

Is it possible to attach "traits" to a current array of objects using TypeScript?

I have a variety of object types that I need to manipulate within an array consisting of those object types. type AB = { a:number, b:number} type CD = { c:number, d:string} type DE = { d:number, e:boolean} let state: AB[] = [] function onStateChange(newSt ...

Steps for updating the value of a button in Typescript and React

I currently have a button that manages my language switcher, configured to handle cookies, URL changes, and now I want it to update the translations on the page as well. The <img> tag is utilized for changing the country flag. < ...

The 'target' property is not found on the type 'KeyboardEventHandler<HTMLInputElement>'

My Visual Studio Code is giving me an error in my onKeyUp function when I try to access the input target and retrieve its value. import React from 'react'; import styles from './styles.module.scss'; export function Step3() { ...

In my current project, I am working with Knockout and TypeScript but I am encountering difficulties in firing the window-resize event

Instead of using jquery, I prefer working with a custom handler for the $(window).resize(function () { ... event. If there is a way to achieve this without relying on jquery, please feel free to share it in the comments below. The code snippet below show ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...

The output of `.reduce` is a singular object rather than an array containing multiple objects

Building on my custom pipe and service, I have developed a system where an array of language abbreviations is passed to the pipe. The pipe then utilizes functions from the site based on these abbreviations. Here is the parameter being passed to the pipe: p ...

Is it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...

Angular - Switching Displayed Information

I am currently working with Angular 4 and I am attempting to switch between contenteditable="true" and contenteditable="false" Here is what I have so far: <h1 (dblclick)="edit($event)" contentEditable="true">Double-click Here to edit</h1> Al ...

What could be causing the cyclic dependency problem after upgrading to Angular 9?

I am experiencing an issue with a specific file containing the following code: import { Injectable } from '@angular/core'; import { I18n } from '@ngx-translate/i18n-polyfill'; import { isNumber } from 'lodash'; import { Confir ...

Using Typescript: Compiling specific files within a directory

According to the documentation for typescript, we have the option in tsconfig.json to manage input files using either the files property where all files are listed, or with the exclude property. I have organized all my source files within a directory named ...

Unit tests are failing to typecast the Angular HTTP GET response in an observable

I've been delving into learning about unit testing with Angular. One of the challenges I encountered involved a service method that utilizes http.get, pipes it into a map function, and returns a typed observable stream of BankAccountFull[]. Despite ...

Angular 2: Integrating a service into a class

I am working on an Angular class that represents a shape. My goal is to be able to create multiple instances of this class using a constructor. The constructor requires several arguments that define the properties of the shape. constructor(public center: ...

Ways to display all current users on a single page within an application

I have come across a project requirement where I need to display the number of active users on each page. I am considering various approaches but unsure of the best practice in these scenarios. Here are a few options I am considering: 1. Using SignalR 2. ...

The POST requests on Next JS Mock API endpoints include parameters passed in the req.body

I am currently running Next JS API tests using jest with a custom testClient. The code for the testClient is as follows: import { createServer } from 'http'; import type { NextApiHandler } from 'next'; import type { __ApiPreviewProps } ...

Navigating through the nested object values of an Axios request's response can be achieved in React JS by using the proper

I am attempting to extract the category_name from my project_category object within the Axios response of my project. This is a singular record, so I do not need to map through an array, but rather access the entire object stored in my state. Here is an ex ...

Angular4 Leaflet Map encountering errors

Here is the template: <div id="mapid" style="height: 500px"></div> After installing Leaflet and the typings for Leaflet, I encountered an error stating that the map container was not found. To solve this, I added its import. This is the cont ...