Injecting a 'distinct symbol' into a function

I have a couple of inquiries regarding the code provided below:

  1. Can something other than an enum be passed as a Param?
  2. Is there a way to achieve more specific typing during execution of e that specifies the param key?

Ideally, both of these issues can be addressed using a unique symbol type such as:

new (class extends Symbol)('alpha')

enum Params {
    alpha = 'alpha'
}

const defaultParam = <T> (param: Params) => {
    return (a: { [param]: T }): T => { 
        throw new Error('need param')
    }
}

const e = defaultParam<number>(Params.alpha)
e({ beta: 2 })

Below is the error message:

Argument of type '{ beta: number; }' is not assignable to parameter of type '{ [param]: number; }'.
  Object literal may only specify known properties, and 'beta' does not exist in type '{ [param]: number; }'.

And with param: string:

A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.

Answer №1

No need for any symbols here!

const initialParameter = <G extends string, T>() => {
    return (input: Record<G, T>): T => {
        throw new Error('parameter required')
    }
}

const y = initialParameter<'beta', number>()

Alternatively, if a parameter is needed as a variable:

const initialParameter = <T>() => {
    return <G extends string>(variableParam: G) => {
        return (input: Record<G, T>): T => {
            throw new Error('Need ${variableParam}')
        }
    }
}

const z = initialParameter<number>()('beta')

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

implementing image loading functionality in Next.js using TypeScript

I recently started working on building a website using NEXT.js with typescript. I have limited experience with typescript and currently facing an issue related to ImageLoader as cloudflare pages don't support the default image loader. However, I am un ...

Tips for dynamically calling a property member of a function type in Typescript

How can I determine if a member is a function in TypeScript? Is dynamic typing discouraged in TypeScript? function checkIfFunction<T, K extends keyof T>(obj: T, propName: K) { if (typeof obj[propName] === "function") { obj[p ...

The issue with prerendering leads to a SyntaxError: Forbidden to utilize import statement in a non-module context

When attempting to prerender my Angular code by running prerender.ts as outlined in this tutorial, I encountered an issue. The error message appeared when trying to execute it using ts-node prerender.ts: import 'zone.js/dist/zone-node'; ...

`A bug in my Angular 4 application causes a TypeError when hosted on IIS`

After hosting an Angular 4 app on IIS, it seems there is an issue when accessing the app from machines other than the ones used for development. An error message " 'Uncaught TypeError: undefined is not a function' common.es5.js:3084" appears on t ...

Transcompiling TypeScript for Node.js

I'm in the process of developing a Node project using Typescript, and I've configured the target option to es6 in my tsconfig.json file. Although Node version 8 does support the async/await syntax, Typescript automatically converts it to a gener ...

When an Angular service is created, its properties are not immediately configured

My current task involves testing an Angular (4.1) service that looks like this: @Injectable() export class JobService { private answerSource = new Subject<AnswerWrapper>(); answer$ = this.answerSource.asObservable(); answer(answer: AnswerWra ...

Connecting peers to servers using WebRTC

While attempting to set up a peer-to-server connection with WebRTC, I struggled due to the lack of TypeScript types in node-webrtc. This made it difficult to add collaborators and disrupted the codebase. Is there an alternative method for establishing a ...

Is there a way to establish a data type using a specific key within the Record<K, T> structure in Typescript?

Imagine the scenario where an object type needs to be created and linked to a specific key specified in Record<Keys, Type>. Let's say there is a type called User, which can have one of three values - user, admin, or moderator. A new type called ...

Limit function parameter types to object keys

Is it possible to constrain my function parameter to match the keys of an object? I want to achieve something similar to this: export const details = { x: { INFO_x: 'xxx' }, y: { I ...

Utilize the global theme feature within React Material-UI to create a cohesive

I'm feeling a bit lost when it comes to setting up React Material-UI theme. Even though I've tried to keep it simple, it's not working out for me as expected. Here is the code snippet I have: start.tsx const theme = createMuiTheme({ ...

Guide to accessing a newly opened window from a different domain originating from the current window

Currently working on an Angular project, I am facing a scenario where I have a link on page A that directs users to a different origin page B. The HTML code for the link is shown below: ... <a href="https://another.origin"> PAGE B </a> ... On ...

What is the best way to showcase a firebase "row" containing two columns within an Ionic 2 application?

Currently in the process of developing an app to keep track of assignments using Ionic 2/Typescript and Firebase as the backend database. The main page displays a list of assignments retrieved from the database. Creating a new assignment requires the user ...

Can a unique intrinsic type be created from scratch?

Ever since template literals were introduced in Typescript (PR), we've had access to various useful functions in our types: Uppercase Lowercase Capitalize Uncapitalize For more information, refer to the official documentation. Although it may seem ...

The attribute on the label fails to trigger any action on the linked input upon clicking, due to the binding of the id and for

My component is designed to display a checkbox and label, with inputs for id, name, label, and value. Here's the code: <div class="checkbox col-xs-12" *ngIf="id && name && label && value"> <input type="checkbox" ...

There is no index signature in the type 'string | number | EnvType' that accepts a parameter of type 'string'

Can someone help me troubleshoot this issue with config[curr][targetEnv] ??? interface EnvType { dev: string; staging: string; production: string; } type Config = { [key: string]: number | string | EnvType; }; const config: Config = { network ...

I noticed that when using Nestjs in conjunction with Typeorm, there is an unexpected addition of "_rid" to my relation name

I'm currently working on a project that involves users with both student and instructor roles, along with their relationships. Everything was running smoothly until I encountered an issue where I am unable to post content related to these relationship ...

The proper injection of the NestJS module is essential for seamless functionality

When working with Nest, I created a new module using the command nest g module UserModule src/user-module/user.resolver.ts contains the following code: import { Query, Resolver } from '@nestjs/graphql'; import { UserService } from './user.s ...

Utilizing objects as values with `react-hook-form`

About the Issue I'm facing an issue with a component that utilizes an object as its value. My goal is to integrate this component with react-hook-form The challenge arises when react-hook-form considers my object as a nested form control Background ...

Getting style information from a parent element in ReactJS involves accessing the parent component's CSS properties

Is there a way to automatically change the color of text inside a button component based on the color of the button itself? I'm trying to access the parent element's color in my text component. Here's what I have: const MyText = (props) => ...

Error: Failed to fetch the data from the Firebase database

I have recently added an edit button to my product list, but when I click on it, the form page opens with no data populated. Upon debugging in my product.service.ts file, I noticed that it outputs null when using console.log(p). I believe this is where the ...