Is there a method to create a typecheck for hasOwnProperty?

Given a certain interface

interface Bar {
  bar?: string
}

Is there a way to make the hasOwnProperty method check the property against the defined interface?

const b: Bar = { bar: 'b' }
b.hasOwnProperty('bar') // works as expected
b.hasOwnProperty('ba')  // wish this would throw an error saying "ba" does not exist in Bar

I have thought about using

b.bar !== undefined

but this is not exactly the same since theoretically bar could exist but be assigned to undefined, like so:

const b: Bar = { bar: undefined }
b.hasOwnProperty('bar') // true
b.bar !== undefined     // false

I realize I could create my own function that wraps hasOwnProperty with the correct type signature such as

has<T extends object>(obj: T, key: keyof T): boolean
, but I am curious if there is a more built-in alternative.

Answer №1

When using obj.hasOwnProperty(), it verifies the presence of a property, rather than checking its value. This eliminates the need for type checking.

It may be beneficial to reconsider your approach. When creating an interface, it is important to have well-defined shared properties. Sharing properties in an interface without understanding their types defeats the purpose of utilizing interfaces.

Answer №2

You seem to be confusing two different concepts here.

TypeScript's type system is only present during compilation, whereas the hasOwnProperty() function is executed at runtime.

During runtime, JavaScript does not provide type information since it is a dynamically typed language.

It is not recommended to perform such tests because JavaScript (and therefore TypeScript) supports dynamic typing, allowing for duck typing.

Consider the following scenario:

function doSomething(x: Foo) {
  // ...
}
let y = { foo: 'foo', fo: 'fo' }
doSomething(y)

Should doSomething() produce an error in this situation?

When consuming doSomething(), focus on what you require rather than mandating that the caller provide exactly what is needed.

On the other hand, the TypeScript compiler identifies common mistakes like typos and will generate a compile-time error with code like the following:

// Argument of type '{ fo: string; }' is not assignable to parameter of type 'Foo'.
// Object literal may only specify known properties, and 'fo' does not exist in type 'Foo'.
doSomething({ fo: 'foo' })

This error occurs only when passing in object literals directly. The following code does not trigger an error:

let y = { fo: 'foo' }
doSomething(y)

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

Update the label for the weekday on Material UI picker

Is there a way to change the weekday display in Material UI DatePicker from single initial (M, T, W, T, F, S, S) to three-letter initials (MON, TUE, WED, etc)? I want to customize it in my component like this: <DatePicker disablePast disableTool ...

Guide to transmitting and managing a JSON document utilizing JavaScript

When working on the server side, I receive a simple JSON file via REST that contains various IDs. Here is an example: [ { "_id": "5825a49dasdasdasd8417c1b6d5", } "_id": "dfsdfsdf4960932218417c1b6d5", } "_id": "23434344960932218417c1b6d5", },] To handle t ...

Ways to properly release file descriptors in write streams

I'm currently working on a code snippet that showcases what I'm aiming to achieve: const fs = require('fs'); var stream = fs.createWriteStream('/tmp/file'); stream.once('open', function(fd) { for (var i = 0; i ...

Having trouble with the jQuery toggle functionality not working as expected

I'm implementing a function where a div should increase in height and opacity when clicked, and then revert back to its original state when clicked again. I used the toggle function for this purpose, but the issue is that the button disappears when th ...

Optimal strategy for waiting until all service calls have completed and returned responses within an Angular controller

Is there a way in Angular to determine when all service calls have completed so that I can stop a loading bar in the controller? ...

Nested solution object populated with promises

Looking for a solution similar to the npm libraries p-props and p-all, but with the added functionality of recursively resolving promises. const values = { a: () => Promise.resolve(1), b: [() => Promise.resolve(2)], c: { d: () =&g ...

Is there a way to incorporate a trace in Plotly while also arranging each data point along the x-axis in a unique custom order?

I am facing a challenge in creating a line graph that displays (x, y) coordinates where the x axis represents a date and the y axis represents a value. The dates are formatted like DD-MM-YYYY, for example, 15-04-2015. My initial trace is added with the fo ...

Guide to customizing the default scrollbar colors in Nextjs

When browsing websites like tailwindcss.com or https://developer.mozilla.org/ in Chrome and Firefox, you may have noticed that they utilize the default scrollbar style but allow users to change its colors through a dark/light mode button. The appearance of ...

Enhancing UI Design with Styled-Components and Material Components using Media Queries

Struggling to grasp media queries with MUI and styled components. Take a look at the following syntax using styled-components: Syntax 1: const Video = styled.video` width: 860px; @media ${device.mobileSM} { width: 90%; } `; Additionally, there ...

Is it possible to swap out one ID value for another using JavaScript?

I am facing two issues 1) First Issue I need to update the current id value with a new one. Whenever the a tag is clicked, an event in jQuery code should be triggered to change the id value. For example, When a button is clicked <div class="video" i ...

Tips for converting a string array constant into a union type

I have a string array that I want to use to create a new type where the properties correspond to the elements in the array. There are different types of arrays and I have a function that generates different output types based on the input array. const RG ...

Create a directive for AngularJS that utilizes SVG elements without using the deprecated

I rely heavily on directives for creating and manipulating intricate SVGs. With the deprecation of "replace" in directive factories starting from version 1.3.??, I am facing a dilemma on how to construct a valid SVG without utilizing replace: true in my di ...

Is it possible to submit a POST method without using a form?

I am looking to create a button that functions similar to the "Follow" buttons found on social networks. The challenge I face is that I need to refresh the page when the user clicks the button, as the content of the page heavily depends on whether the user ...

Issue with displaying selected value and options in Mat-select when using formarray - Reactive forms in Angular

I've been working on the code below to create dropdowns, but I'm having trouble getting the selected value and options to show up in the dropdowns. Can you help me figure out what's wrong with the code? Component code testForm: FormGroup; ...

Angular6 Observables used in API service with dynamic arguments

In order to achieve the desired behavior, I am trying to implement a system where when a user selects a label from a dropdown menu, an API call is made with that specific label as an argument. Subsequently, a chart should be redrawn using the data received ...

Cloning a file input does not retain the uploaded file in the cloned input. Only the original input retains the uploaded file

Whenever I duplicate an input type file, I encounter an issue where the uploaded file from the duplicated input is also linked to the original input. It seems like the duplicate input is somehow connected to and taking files for the original one. This is ...

Creating a sleek horizontal drop-down navigation menu using Bootstrap 5 and CSS

Attempting to design a horizontal dropdown menu for small screens has been a challenge. However, all the resources I've come across seem to be outdated and ineffective. ...

Exploring limitless possibilities with Vue slot manipulation

Imagine I am looking to develop a multi-layered Component for reusability, similar to a 'Tab' UI. This would allow developers to use it like this: <tabs> <tab label="My First Tab"> Content for first tab which could co ...

The function crypto.randomUUID() does not exist in the Vitest library

vite.config.ts import { sveltekit } from '@sveltejs/kit/vite'; const config = { plugins: [sveltekit()], test: { include: ['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], environment: 'jsdom', glo ...

Utilize devextreme for uploading files

Currently, I am trying to implement an upload document feature using Dev-Extreme, but I keep encountering an error onFileUpload(event){ this.file = event.target.files[0] } <dxi-column [showInColumnChooser]="false" type="buttons" [width]="100 ...