Utilize the useTheme type from Emotion Js within ReactJs using Typescript

Greetings! As a newcomer to typescript, I find myself with a query regarding the use of Theme in emotionJs. Here's the snippet of code that has been causing me some trouble:

const GlobalStyle: React.FC = (props) => {
  const Theme = useTheme();
  return (
    <Global
      styles={css`
        @import url('https://fonts.googleapis.com/css?family=Poppins&display=swap');
        @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');

        /* Rest of the CSS properties */

        body {
          background: ${Theme.colors.background};
          color: ${Theme.colors.text};
          transition-duration: 0.4s;
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto',
            'Oxygen', 'Ubuntu', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
            sans-serif;
        }
      `}
    />
  );
};

Unfortunately, when running this code, I encountered the following error:

Object is of type 'unknown'.ts(2571)

This issue seems to stem from the uncertainty around declaring the type for my constant Theme while using useTheme.

I am aware that specifying the type for the theme variable is where the problem lies, but I'm uncertain about the correct approach to resolve this dilemma. Any guidance on this matter would be greatly appreciated!

Answer №1

Here's the solution I implemented:

  1. To address the issue, I created an emotion.d.ts file following the instructions provided here. The content of my file looks like this:
import '@emotion/react';
    
declare module '@emotion/react' {
  export interface Theme {
    colors: {
      blue: string[];
      gray: string[];
      primary: string;
      secondary: string;
      background: string;
      white: string;
    };
    space: string[];
    border: { 
      radius: string; 
    };
  }
}
  1. I ensured that the file was located in a folder included by Typescript, which for me was the src folder.

This is how my tsconfig.json file is set up:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["DOM"],
    "jsx": "preserve",
    "noEmit": true,
    "isolatedModules": true,
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "jsxImportSource": "@emotion/react"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "public", ".cache", "gatsby*"]
}

The only Emotion-specific configuration I had to make was setting jsxImportSource as outlined here.

And that's all there was to it!

Answer №2

This is how I accomplished it:

const design = {
  fontColor: '#000000',
  background: '#ff0000',
};

type DesignType = typeof design;

const GlobalDesign: React.FC = (props) => {
  const Theme = useTheme<DesignType>();
  return (
    <Global
      styles={css`
        ...
      `}
    />
  );
};

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

Discovering the current page using ons-navigator in Onsen UI

I am currently attempting to determine the page I am on while using the popPage() function with Onsen UI's ons-navigator. I have tried the following methods, but they always return false regardless: this.navigator.nativeElement.popPage().then((page: a ...

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 ...

Unable to loop through using ngFor

I have a component that retrieves data from the back-end and groups it accordingly. Below is the code snippet: getRecruitmentAgencyClientPositions(): void { this._recruitmentAgencyClientsService.getRecruitmentAgencyClientPositions(this.recruitmentAge ...

Is there a way to retrieve all potential string literals from an Array<>?

Can something similar be achieved in TypeScript? const options: Array<'Option1' | 'Option2' | 'Option3'> = []; // specify all available options: 'Option1' | 'Option2' | 'Option3' as show ...

Having trouble with the onChange function within the rc-field-form wrapper

I created a wrapper for the Field component from the rc-field-form package as shown below: import * as React from "react"; import Form from "rc-field-form"; import type { FieldProps } from "rc-field-form/lib/Field"; const { F ...

The paths configuration in tsconfig.json is not functioning as anticipated

I've been encountering a module not found error while trying to work with jasmine-ts. To troubleshoot, I decided to use tsc and inspect my folder structure: \src\app\... \src\tests\... To address this issue, I created a ...

Is it possible to conceal a table element using [hidden] in Angular 2?

I have a table that includes buttons for adding rows. Table application Question: I am looking to hide the table element and add a show click event on the "Add" button. Here is an example of the HTML code: <div class="col-md-12"> <div class="pa ...

Resolving the problem of <Link> error in React with Typescript using react-router-dom

Currently, I am facing an issue with the 'react-router-dom' library. This is my first experience using React with Typescript; Everything was functioning properly until I introduced the from 'react-router-dom', which caused the entire ...

order by truthiness

I am working with an array of the following class: export class Tests { id: number; name: string; createdAt: any; succress: boolean; constructor(id: number, name: string, createdAt: any, success: boolean) { this.id = id; this.name = nam ...

Type-constrained generic key access for enhanced security

While attempting to create a versatile function that retrieves the value of a boolean property using a type-safe approach, I encountered an issue with the compiler not recognizing the type of my value. type KeyOfType<T, V> = keyof { [P in keyof T a ...

Struggling with getting render props to work in Next.js version 13

Looking to develop a custom component for Contentful's next 13 live preview feature in the app directory, I thought of creating a client component that can accept a data prop and ensure type safety by allowing a generic type to be passed down. Here is ...

Is it possible to view the list of errors displayed by vscode when opening a JS file exclusively through the terminal?

Is there a default configuration file that vscode uses to display errors and warnings? I want to identify all issues in my JavaScript project. I don't have any jsconfig.json or tsconfig.json files, only using the //@ts-check directive in some files. ...

The object's null status remains uncertain even after being checked for null

Currently, I am working with Typescript 2.8 This is the code snippet that I have: class Wizard extends React.Componenet { private divElement: null | HTMLDivElement = null; componentDidUpdate(_: IWizardProps, prevState: IWizardState) { i ...

Protractor for Angular 2: Pausing execution until specified element obtains a specified class

Looking for a method to delay my e2e test (angular2 project) until the targeted element receives a specific css class. Is there an alternative approach without using browser.wait() or browser.sleep()? ...

Sending parameters in GraphQL with Typescript results in an empty set of curly braces being returned

I am new to learning GraphQL with Typescript and I am trying to pass an argument in a GraphQL function to return something dynamically. I have been struggling with this issue for the past hour and could not find any solutions. Here are the relevant code sn ...

The child component stays consistent across all Angular routing configurations

Currently diving into Angular routing, I've added two routerLinks to the parent component. It appears that routing is set up correctly, but for some reason the page remains unchanged. Parent Child const childrenRoutes: Routes =[ {path: 'overvi ...

Leveraging Typescript in Firebase Cloud Functions to effectively work with intricate interfaces

When querying a collection on the app side, I am able to automatically cast the result as an interface using Positions constructor that takes in interface IPosition. However, attempting to do the same on the cloud functions side prevents the functions fro ...

Entering the appropriate value into an object's property accurately

I am currently facing an issue with typing the value needed to be inserted into an object's property. Please refer below. interface SliceStateType { TrptLimit: number; TrptOffset: number; someString: string; someBool:boolean; } inter ...

I am looking to extract only the alphanumeric string that represents the Id from a MongoDB query

Working with mongoDB, mongoose, and typescript, I am facing an issue where I need to preserve the document ids when querying. However, all I can retrieve is the type _id: new ObjectId("62aa4bddae588fb13e8df552"). What I really require is just the string ...

Error: Unable to locate the reference for "foo" while utilizing TypeScript in combination with Webpack

My Chrome extension is functioning properly when using JavaScript alone. However, when attempting to incorporate TypeScript with Webpack, I encountered an issue where the function foo could not be found. Uncaught ReferenceError: foo is not defined Here ...