Expanding the capability of a function by inheriting properties of either type any or unknown

Can you explain why the values of P1 and P2 are different in these type definitions?

type P1 = (() => 22) extends {[k:string]:any} ? 1:2 //`P1 == 1`
type P2 = (() => 22) extends {[k:string]:unknown} ? 1:2 //`P2 == 2`

Answer №1

View the Breaking Change: { [k: string]: unknown } is no longer a wildcard assignment target for an authoritative response.

The concept of index signature {[k: string]: any} in Typescript has specific behaviors, allowing it to be assigned to any object type. In scenarios where types like () => 22 lack implicit index signatures, attempting to assign () => 22 to {[k: string]: unknown} results in an error. The special permissive behavior only emerges when the property type is any:

let anyRec: { [k: string]: any };
anyRec = () => 22; // permissible

let unkRec: { [k: string]: unknown };
unkRec = () => 22; // trigger an error

This explains the difference between P1 and P2.

Visit the Playground link for the code snippet

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

The 'ref' attribute is not found within the 'IntrinsicAttributes' type

I'm currently working on a TypeScript project using React. Although the code is functional, I keep encountering compiler errors with my ref. Here's an example of the code: Firstly, there's a higher-order component that handles errors: expor ...

"ENUM value is stored in the event target value's handle property

My issue lies with the event.target.value that returns a 'String' value, and I want it to be recognized as an ENUM type. Here is my current code: export enum Permissions { OnlyMe, Everyone, SelectedPerson } ... <FormControl> & ...

Issue: Attempting to assign a 'boolean' variable to a type of 'Observable<boolean>' is not compatible

I am currently working on the following code: import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router'; import {Observable} from 'rxjs' ...

Angular 4's unique feature is the ability to incorporate multiple date pickers without the

Is there a way to implement a multiple date picker using Angular 4 and TypeScript only? I came across one solution but it seems to only support Angular 1. Thank you in advance! ...

Tips for incorporating ACE Editor syntax highlighting rules into an Angular application

I am attempting to create custom highlighter rules by referencing examples from here and here. import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import * as ace from 'ace-builds'; import 'ace-builds/src- ...

How to deliver various static files in NestJS using different paths and prefixes?

I've set up static file serving for developer documentation using the following code: app.useStaticAssets(docsLocation, { prefix: "/docs/" }) Now I have another directory with more static content that I want to serve. Is it possible to serve from ...

Angular 12's BehaviorSubject should have been empty object array, but it unexpectedly returns undefined

Exploring different scenarios with a livesearch functionality: No user input (observable = undefined) No results found (observable = empty array) Results found (observable = non-empty array) The issue lies in how my behavior subject interprets an empty a ...

Iterating through an array and setting variables according to asynchronous code

I have created a function to loop through an array, call a promise, and update a variable based on the result. The code seems to be functioning correctly, but I am wondering if there is a more optimal way to write it. Any suggestions are appreciated. Tha ...

When it comes to TypeScript, one can always rely on either event.target or event

I'm a beginner with TypeScript and currently in the process of refactoring an arrow function within React.js. Here is the current implementation: handleChange = (event): void => { const target = event.target || event.srcElement; this.s ...

Guide on troubleshooting *.ts files in an ionic 2 project using Chrome's inspect devices feature

After successfully creating my Ionic 2 application for Android using the command "ionic build android", everything seems to be working fine. I have been debugging the app by using Chrome inspect devices, but now I am facing an issue. I am trying to debug ...

When attempting to import a component from an external library in React/Next, you may run into an error that states: "Element type is invalid: Expected a string or

I am currently working on developing a React components library that can be seamlessly integrated into a NextJs project. The library includes a versatile "CmsBlock" component which takes a type and data as inputs to generate either a Paragraph or ZigZag co ...

How to Utilize an Array from Observable Object in Angular 2 with ngFor and Async Pipe

I am currently learning about the utilization of Observables in Angular 2. Here is a snippet of code from a service I am working with: import {Injectable, EventEmitter, ViewChild} from '@angular/core'; import {Observable} from "rxjs/Observab ...

How can I simulate or manipulate the element's scrollHeight and clientHeight in testing scenarios?

In my JavaScript code, I have a function that checks if an HTML paragraph element, 'el', is a certain size by comparing its scrollHeight and clientHeight properties: function isOverflow(element: string): boolean { const el = document.getEleme ...

Determining the data type of a property within an interface using TypeScript

Is there a way to extract the type from an interface based on its property name in order to use it in a Record? I am struggling with the syntax needed to retrieve the type by property name. My goal is to make this process more future-proof so that if the i ...

What is the best way to obtain an error as an object when subscribing to an HTTP GET request

I am working on an asp.net core webApi along with an Angular9 WebApp. My goal is to retrieve the error in a subscribe as an object rather than just a string. this.http.post<TestSystem>(this.url, testsystem).subscribe((result) => { // do someth ...

The correct way to add to a string array that has been passed as props to a functional component

There is a parent component that establishes a useState hook with a string array. Then, there is a child component tasked with updating the string array. To accomplish this, both the string array and the useState function are passed to the child component. ...

Verifying the accuracy of a React Component in interpreting and displaying a path parameter

I have the following React/Typescript component that is functioning correctly. However, I am struggling to write a test using testing-library. My goal is to verify that it properly receives the level parameter and displays it on the page: import React from ...

Ensure the presence of a value in an array using Angular

I need to check if any of the "cuesData" have values or lengths greater than 0. However, in my current code, I can only evaluate the first array and not the rest. https://i.sstatic.net/bMpvg.jpg TS checkValues(values) { const result = Object.values ...

Implementing the strictNullCheck flag with msbuild

Can strict null checks be enabled when compiling using msbuild? I see in the documentation that the compiler option is --strictNullChecks, but I couldn't find any specific entry for it on the msbuild config page. Is there a method to activate this f ...

TypeScript encountered an error with code TS2305, stating that the module "constants" does not have any exported members

My Vite + React + TypeScript application has the following structure: src constants a.ts b.ts index.ts components Comp.tsx tsconfig file with "baseUrl": "src" The content of a.ts is as follows: export const ARRAY = ...