When using Typescript, I am encountering an issue where declared modules in my declaration file, specifically those with the file

One of the declarations in my ./src/types.d.ts file includes various modules:

/// <reference types="@emotion/react/types/css-prop" />
import '@emotion/react';
import { PureComponent, SVGProps } from 'react';

declare module '*.svg' {
  export class ReactComponent extends PureComponent<SVGProps<SVGSVGElement>> {}
}
declare module '*.ttf';
declare module '*.eot';
declare module '*.woff';
declare module '*.woff2';

Upon running tsc --noEmit, errors like ...

src/fonts/fonts.ts:39:31 - error TS2307: Cannot find module './pt-sans-v12-latin-ext_latin-regular.woff' or its corresponding type declarations.

39 import PTSansregularWOFF from './pt-sans-v12-latin-ext_latin-regular.woff';
                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/fonts/fonts.ts:40:32 - error TS2307: Cannot find module './pt-sans-v12-latin-ext_latin-regular.woff2' or its corresponding type declarations.

40 import PTSansregularWOFF2 from './pt-sans-v12-latin-ext_latin-regular.woff2';
                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/layouts/default/NavigationBar.tsx:4:41 - error TS2307: Cannot find module '../../images/brand.svg' or its corresponding type declarations.

4 import { ReactComponent as Brand } from '../../images/brand.svg';
                                          ~~~~~~~~~~~~~~~~~~~~~~~~

... are displayed.

This is my tsconfig.json:

{
  "include": ["./src/**/*", "./.gatsby/**/*", "./*.ts", "./plugins/**/*"],
  "files": ["./src/types.d.ts"],
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "lib": ["dom", "ES2017", "ES2019"],
    "jsx": "react-jsx",
    "strict": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "noEmit": true,
    "skipLibCheck": true,
    "moduleResolution": "node",
    "resolveJsonModule": true
  }
}

This is the structure of my file tree: https://i.stack.imgur.com/Fv1pF.png

How can I ensure Typescript locates the corresponding type declarations?

Interestingly, defining the interface Theme in @emotion/react within my types.d.ts has an effect on other parts.

Answer №1

This is how I utilize it:

declare module '*.jpg';
declare module '*.png';
declare module '*.woff2';
declare module '*.woff';
declare module '*.ttf';

declare module '*.svg' {
  import React = require('react');

  export const ReactComponent: React.SFC<React.SVGProps<SVGSVGElement>>;
  const src: string;
  export default src;
}

Then, I incorporate it in this manner:

import { ReactComponent as Icon } from './icons/icon.svg';
import AnotherImage from './images/header.jpg';

Answer №2

In order to allow the loading of svg and png files, I added the following snippet to a file named custom.d.ts located in the root directory of the project:

declare module '*.svg' {
  import * as React from 'react';

  export const ReactComponent: React.FunctionComponent<React.SVGProps<
      SVGSVGElement
  > & { title?: string }>;

  const src: string;
  export default src;

}
declare module "*.png" {
  const value: any;
  export default value;
}

Although I am not an expert, this code snippet appears to define how TypeScript should handle imports of SVG and PNG files within the project.

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

Enabling Event bus suggestions for Typescript: A step-by-step guide

Hello, I've encountered an issue while attempting to add types for the TinyEmitter library. Specifically, I need to define two methods. First: addEventListener(e: string, (...args: any[]) => void): void; Second: emit(e: string, ...args: any[]): vo ...

I'm attempting to retrieve mlab data in the console using node.js, but unfortunately encountering an error

I came across this helpful YouTube tutorial:https://www.youtube.com/watch?v=PFP0oXNNveg&t=460s. I followed the steps outlined in the video and made necessary code adjustments based on current updates found through a Google search (to resolve errors enc ...

Utilizing asynchronous methods within setup() in @vue-composition

<script lang="ts"> import { createComponent } from "@vue/composition-api"; import { SplashPage } from "../../lib/vue-viewmodels"; export default createComponent({ async setup(props, context) { await SplashPage.init(2000, context.root.$router, ...

What do you do when schema.parseAsync cannot be found?

Currently facing an issue with zod validation in my Node.js environment, specifically encountering the error: TypeError: schema.parseAsync is not a function Despite attempting various solutions like re-importing and troubleshooting, I am unable to resol ...

The attribute 'name' cannot be found within the class 'MyComponent'

I'm a beginner in Angular2 and I have no previous knowledge of version 1. Can you help me understand why this error is occurring and guide me on how to fix it? import { Component } from 'angular2/core'; @Component ({ selector: 'my- ...

What about combining a fat arrow function with a nested decorator?

Trying to implement a fat arrow function with a nestjs decorator in a controller. Can it be done in the following way : @Controller() export class AppController { @Get() findAll = (): string => 'This is coming from a fat arrow !'; } Wh ...

Issue: React cannot render Objects as children (received: [object Promise]). If you intended to display multiple children, please use an array instead. (Next)

My dilemma is this: I am trying to display my GitHub repositories on a React component, but I keep encountering the following error: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, u ...

Can you determine the size of an unknown array in TypeScript?

Currently diving into TypeScript and tackling some TDD challenges. Within my model file, I'm working with a property named 'innovatorQuotes' that should be an array containing strings with a fixed length of 3. I'm struggling to nail dow ...

Angular8 does not recognize custom paths that have been added to the tsConfig file

Hey there! I'm facing an issue with Angular not recognizing a custom path I added to my tsConfig file. It seems like Angular already has a baseUrl property set to ./, starting from the current folder where the tsConfig file is located. The code snippe ...

Creating an interface that extends the Map object in TypeScript to maintain the order of keys

After learning that the normal object doesn't preserve key order in TypeScript, I was advised to use Map. Nevertheless, I'm struggling to figure out how to assign values once I've declared the interface. Take a look at my approach: Coding ...

Is there a way for me to receive the status code response from my backend server?

My component makes a call to a servlet, which then sends a POST HTTP request to the backend (using Spring Boot). I want the backend to return the status of the POST request that was sent earlier. This is my code: res= this.CS.postcompetenze(this.comp) Th ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

Determine if the "type" field is optional or mandatory for the specified input fields in Typescript

I need to determine whether the fields of a typescript type or interface are optional or required. export type Recommendation = { id?: string, name: string, type?: string, tt: string, isin?: string, issuer: string, quantity?: nu ...

Using TypeScript, Material UI introduces a new property to the primary object on the palette

Experimenting with the customization of MUI v5 theme has been a fun challenge in my current project. I have successfully tailored the theme to suit my requirements so far, but now I am faced with the task of adding a new property to the primary object defi ...

Facing a problem with querying interfaces and types in TypeScript

My goal is to pass a variable to an RTK Query API service that uses a typescript interface: const device_id: unique symbol = Symbol(props.id); const { data: device, isFetching, isLoading, } = useGetAssetsByIdQuery(device_id, { pollingInterv ...

Assistance for Angular 2 Style Guide within Atom: Feature Needed!

My manager uses Atom with a set of eight plugins specifically designed for Angular development. I have the same plugins installed on my system, but I seem to be missing a feature that he has. We're unsure which plugin or preference setting is required ...

I encountered a mistake: error TS2554 - I was expecting 1 argument, but none was given. Additionally, I received another error stating that an argument for 'params' was not provided

customer-list.component.ts To load customers, the onLoadCustomers() function in this component calls the getCustomers() method from the customer service. customer.servise.ts The getCustomers() method in the customer service makes a POST request to the A ...

Tips for deleting a specific choice with Angular

Having recently started working with Angular2 / TS / ES6, I am struggling to find a solution to my issue. I have a select element with dynamically rendered options using ngFor from an array. These options are meant for selecting attributes for a product. ...

In Typescript, ambient warnings require all keys in a type union to be included when defining method parameter types

Check out this StackBlitz Example Issue: How can I have Foo without Bar, or both, but still give an error for anything else? The TypeScript warning is causing confusion... https://i.stack.imgur.com/klMdW.png index.ts https://i.stack.imgur.com/VqpHU.p ...