Typescript provides the flexibility to construct incomplete or partially valid objects

My attempt to create a partial helper function in Typescript led me to an incorrect version that went unnoticed by Typescript:

Typescript version: 5.2.2

type A = { a: number; b: string };

// incorrect
const buildPartialBad = (key: keyof A, val: A[keyof A]): Partial<A> => ({ [key]: val });
const test1 = buildPartialBad('a', 'hello'); // allows creation of an invalid object

// correct
const buildPartialGood = <K extends keyof A>(key: K, val: A[K]): Partial<A> => ({ [key]: val });
const test2 = buildPartialGood('a', 'hello'); // compile error: Argument of type 'string' is not assignable to parameter of type 'number'

I am puzzled as to why the buildPartialBad function did not trigger any errors.

While searching on StackOverflow and GitHub for similar Partial-related issues, I couldn't find an exact match. It seems like such a simple oversight that it's hard to believe it could be a bug in TS. Perhaps I'm just not fully awake :)

If anyone has an explanation, I would greatly appreciate it. Thank you

Answer №1

Within the confines of the function buildPartialBad, there exists no correlation between the types of the first and second parameters. Therefore, using "a" as the value for the first parameter is permissible (it falls within the scope of keyof A), and assigning "hello" to the second parameter is also acceptable (given that it aligns with the type number | string, which reflects the nature of A[keyof A]). It seems that the lack of strictness in type definitions prevents TypeScript from identifying any issues with the return value – the expansive definition of key (keyof A ["a" | "b"]) and val (A[keyof A] [number | string]) hinder TypeScript's ability to flag inaccuracies.

In a revised version, a relationship has been established between the parameters. By specifying "a" as the initial parameter value, TypeScript expects the corresponding val to be A["a"], translating to a requirement for a number. Consequently, attempting to pass a string would result in an error.

Answer №2

To explain further, when you use buildPartialGood, the code assumes that K is interpreted as the specific string "a". Therefore, A[K] is replaced by A["a"], resulting in a value of number.

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 ValidationSchema Type in ObjectSchema Seems to Be Failing

yup 0.30.0 @types/yup 0.29.14 Struggling to create a reusable type definition for a Yup validationSchema with ObjectSchema resulting in an error. Attempting to follow an example from the Yup documentation provided at: https://github.com/jquense/yup#ensur ...

How is it that I can assign a string value to my declared number object parameter in Typescript?

In my code, I have defined an interface called DateArray: export interface DateArray { year : number; } Within my component, I am declaring a new variable named dateArray like this: private dateArray: DateArray = { year: null }; Then, I am a ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

pressing the button again will yield a new outcome

I am looking to disable a button (material ui) when it is clicked for the second time by setting disabled={true}. Unfortunately, I have not been able to find any examples related to this specific scenario on StackOverflow. <Button onClick={this.s ...

Developing a Javascript object using Typescript

Trying my hand at crafting a TypeScript object from JavaScript. The specific JavaScript object I'm attempting to construct can be found here: https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.2/chess.js In the provided JavaScript example, the obj ...

Dividing component files using TypeScript

Our team has embarked on a new project using Vue 3 for the front end. We have opted to incorporate TypeScript and are interested in implementing a file-separation approach. While researching, we came across this article in the documentation which provides ...

What is the most effective way to eliminate all values in an object key array except for one specific value?

Currently, I am developing an angular project and have encountered an object with the following structure: const obj = { fruits: ['apple', 'orange', 'None'], nation: ['usa'], city: ['New York', ' ...

Trouble navigating through an index of elastic data? Learn how to smoothly scroll with Typescript in conjunction with

I'm currently using the JavaScript client for Elasticsearch to index and search my data, but I've encountered an issue with using the scroll method. Although I can't seem to set the correct index, I am confident in my technique because I am ...

Unable to adjust the x-axis time display in Chart.js

Within my ChartData Component, I am fetching data from an API and displaying it through a chart. The crucial aspect here is the determine Format Logic, which determines the time format of the data. My main challenge lies in changing the time display when s ...

Creating a way for a Node and React application to share classes

I am in the process of developing a Node and React application, both implemented using TypeScript. The directory structure of my project is illustrated below: https://i.sstatic.net/914A1.png My query: Given that I am utilizing the same programming langu ...

Type guard does not narrow down the union type

Explore the following code snippet: type UnionType = 'foo' | 'bar' | 'baz' const obj = { foo: 'huh', bar: 'hmm' } function func(input: UnionType) { if(input in obj) { input } } In ...

Utilizing External Libraries Added Through <script> Tags in React

My goal is to develop a Facebook Instant HTML5 application in React. Following their Quick Start guide, Facebook requires the installation of their SDK using a script tag: <script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></scrip ...

Tips for modifying the UserRepresentation in keycloak REST API response

Whenever we send a GET request to the following URL: https://my-keycloak/admin/realms/test-realm/users We receive a comprehensive list of users who are associated with the test-realm. According to the Keycloak REST API documentation, this kind of respons ...

Angular 14 Observables are not triggering resize events

There seems to be an issue here, as the code is not being triggered at all. The console log is not printing and this.width is not changing. constructor(private host: ElementRef, private zone: NgZone) {} public ngOnInit(): void { this.observer = new Re ...

Convert the generic primitive type to a string

Hello, I am trying to create a function that can determine the primitive type of an array. However, I am facing an issue and haven't been able to find a solution that fits my problem. Below is the function I have written: export function isGenericType ...

Discover the power of catching Custom DOM Events in Angular

When working with an Angular library, I encountered a situation where a component within the library dispatches CustomEvents using code like the following: const domEvent = new CustomEvent('unselect', { bubbles: true }); this.elementRef.nati ...

Learn how to extend components in Typescript and determine necessary arguments. Discover how to apply this knowledge in an Angular use case by extending mat-side-nav

Background: The Angular Material Design component known as mat-side-nav operates in a specific structure for its dynamics: <mat-sidenav-container> <mat-sidenav> </mat-sidenav> <mat-sidenav-content> </mat-sidenav-conten ...

Exploring the integration of Server-Sent Events in Angular

I'm currently working on incorporating Server-Sent Events (SSE) into my testing application. The server side configuration has been completed, and I am utilizing the endpoint (api/v1/sse/document). The aim here is that whenever a scan is performed, I ...

I am experiencing issues with the customsort function when trying to sort a column of

Seeking assistance with customizing the sorting function for a Date column in a primeng table. Currently, the column is displaying data formatted as 'hh:mm a' and not sorting correctly (e.g. sorting as 1am, 1pm, 10am, 10pm instead of in chronolog ...

Harnessing the power of Material-UI's muiThemeable with Typescript

I'm trying to access the current theme colors within a custom React component. The example I'm referencing is from Material UI http://www.material-ui.com/#/customization/themes Despite attempting various approaches, I'm unable to get Typesc ...