No gripes about incorrect typing when extending interfaces

I tried out the following code snippet here

interface OnlyName {
    name: string
}

interface MyTest2 extends OnlyName { 
    age: number
}

let test1: OnlyName;

const setTest1 = (v: OnlyName) => {
    test1 = v
    console.log(test1)
}

let test2: MyTest2 = {
    name: 'test2',
    age: 2,
}

setTest1(test2)

I was expecting an error when calling setTest1() because it is supposed to only accept parameters of type OnlyName. However, to my surprise, it worked even when passing MyTest2.

Why did it not throw an error and is there a way to enforce only accepting OnlyName?

Answer №1

As explained by @Aleksey L, the reason for this issue lies in the structural type system. When passing a literal object to the setTest1 function, TypeScript will raise an error:


setTest1({
    name: 'test2',
    age: 2, //Object literal may only specify known properties, and 'age' does not exist...
})

For more information on excess property checking, you can refer to this link

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

Using Angular to import a JSON file stored locally

I am facing an issue with importing a .json file in my Angular project. The file is located outside the project structure as shown below: | common | configuration.json | angular-app | src | app | my-component | ...

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...

Utilizing Angular 2 for Element Selection and Event Handling

function onLoaded() { var firstColumnBody = document.querySelector(".fix-column > .tbody"), restColumnsBody = document.querySelector(".rest-columns > .tbody"), restColumnsHead = document.querySelector(".rest-columns > .thead"); res ...

Converting an array into an object in Angular for query parameters

In my Angular 12 application, I have an array of objects that I need to convert into query parameters in order to route to a generated URL. The desired query parameters should look like this: Brand:ABC:Brand:XYZ:Size:13x18:Size:51x49x85 [{ "values&q ...

An unexpected 'foo' key was discovered in the current state being processed by the reducer when using redux-toolkit's configure store and a customized store enhancer

I've been working on developing a custom store enhancer to add new values to my root state. However, I've encountered an unexpected key error after delving into the complexities of custom enhancers. While I can see the new state part in devtools ...

The template is displaying the string as "[object Object]"

I've implemented code in my ngOnInit function to fetch the translation for a specific text. The following function is being called: async getEmailTranslation() { const email$ = this.translate.get('SUPPORT_TRANSLATE.EMAIL'); this.emai ...

Verifying input for Numeric TextField

The text field being used is: <TextField variant="outlined" margin="normal" id="freeSeats" name="freeSeats" helperText={touched.freeSeats ? errors.freeSeats : ''} error={touched.freeSeats && Boolean(errors.fre ...

the upward arrow remains steadfast, refusing to evolve into its downward counterpart

Every time I click on "Portfolio", the arrow points downwards. https://i.sstatic.net/Gwf5F.png However, when a submenu appears, the arrow changes to point upwards. https://i.sstatic.net/kFdjr.png If I click on "Portfolio" again, the arrow remains point ...

Is it normal for TypeScript to not throw an error when different data types are used for function parameters?

function add(a:number, b:number):number { return a+b; } let mynumber:any = "50"; let result:number = add(mynumber, 5); console.log(result); Why does the console print "505" without throwing an error in the "add" function? If I had declared mynumber ...

How can I incorporate TypeScript paths into Storybook with Webpack version 5?

Storybook includes a pre-configured Webpack setup. Up until Webpack v4, it was possible to utilize tsconfig-paths-webpack-plugin and define custom tsconfig (or any other plugin) like so: const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plug ...

Unable to access attributes of an undefined value (current state is undefined)

After completing a small project, I attempted to deploy it on Vercel. The project runs smoothly without any errors on my local machine. However, when I tried to run it on the server, I encountered the following error: "Cannot read properties of undefined ( ...

Determining the best application of guards vs middlewares in NestJs

In my pursuit to develop a NestJs application, I aim to implement a middleware that validates the token in the request object and an authentication guard that verifies the user within the token payload. Separating these components allows for a more organi ...

Exploring Observable Functionality in Angular 6

I've been grappling with understanding Angular Observables, but I've managed to get it working. My goal is to fetch data for my dynamic navigation bar. I successfully verified whether the user is logged in or not and displayed the Login or Logout ...

Angular version 7.2.1 encounters an ES6 class ReferenceError when attempting to access 'X' before it has been initialized

I have encountered an issue with my TypeScript class: export class Vehicule extends TrackableEntity { vehiculeId: number; constructor() { super(); return super.proxify(this); } } The target for my TypeScript in tsconfig.json is set to es6: ...

Display a loading GIF for every HTTP request made in Angular 4

I am a beginner with Angular and I am looking for a way to display a spinner every time an HTTP request is made. My application consists of multiple components: <component-one></component-one> <component-two></component-two> <c ...

Signing in to a Discord.js account from a React application with Typescript

import React from 'react'; import User from './components/User'; import Discord, { Message } from 'discord.js' import background from './images/background.png'; import './App.css'; const App = () => { ...

Dynamically apply classes in Angular using ngClass

Help needed with setting a class dynamically. Any guidance is appreciated. Below is the class in my SCSS file: .form-validation.invalid { border: 2px solid red } In my ts file, there's a variable named isEmailValid. When this variable is set to ...

How can you eliminate the first elements of two or more arrays of objects until all of their first elements match based on a specific field?

My Typescript code includes a Map object called `stat_map` defined as const stat_map: Map<string, IMonthlyStat[]> = new Map(); The interface IMonthlyStat is structured as shown below (Note that there are more fields in reality) export interface IMon ...

One way to declare i18next specifically in React's App.tsx file is by following these

In my React App.tsx file, I am looking for a way to declare const { t } = useTranslation() only once. After that, I want to be able to use { t(trans.things) } in my components without having to declare const { t } = useTranslation() again each time. Is t ...

I'm encountering an issue where Typescript is unable to locate the Firebase package that I

I have a TypeScript project that consists of multiple .ts files which need to be compiled into .js files for use in other projects. One of the files requires the firebase package but it's not being found. The package is installed and located inside t ...