Passing a type as an argument in Typescript

How can I pass a type as a parameter in Typescript?

type myType = {}
const passingType = (t: Type) => {
    const x : t = {}
}

passingType(myType);

I keep receiving TypeScript errors.

't' is referencing a value, but it is being used as a type here. Did you mean 'typeof t'?

Also,

'myType' is only a type and cannot be used as a value here.ts(2693).

Do you have any suggestions on how to achieve this?

Answer №1

It is simply not feasible.


When TypeScript code is converted to JavaScript for execution, the static type system, including your myType definition and type annotations, is essentially removed. At runtime, only values are accessible, not types. This means that your code transforms into something like this:

const passingType = (t) => {
    const x = {};
};
passingType(myType);

Since TypeScript types do not exist as values during runtime, there is no concept of a "type of types" like what you referred to as Type. Therefore, achieving this directly is not possible as stated.


Rather than attempting to pass a "type" to a function at runtime, which is ineffective, it's more effective to focus on defining what actions you want to take in pure JavaScript at runtime and then create types to support those actions.

What specific purpose do you intend to achieve with a "type" at runtime? Would you like to use it to verify if a value matches that type? In that case, instead of passing a type, consider passing a type guard function:

type Guard<T> = (x: any) => x is T;
const passingType = <T,>(t: Guard<T>) => {
    if (t(undefined)) {
        console.log("undefined IS of the guarded type T");
    }  else {
        console.log("undefined is NOT of the guarded type T");
    }
}

This can be used as shown below:

function isUndefined(x: any): x is undefined {
    return typeof x === "undefined";
}

passingType(isUndefined); // undefined IS of the guarded type T

function isNumber(x: any): x is number {
    return typeof x === "number";
}
passingType(isNumber); // undefined IS NOT of the guarded type T

function isNumberOrUndefined(x: any): x is number | undefined {
    return isNumber(x) || isUndefined(x);
}

passingType(isNumberOrUndefined); // undefined IS of the guarded type T

Your specific requirements will determine the structure of the argument for passingType. It might involve an entire data structure representing various actions you wish to perform with a "type" at runtime. If the type guard example does not suit your needs, another approach may work better.


In conclusion, TypeScript's static type system is removed during compilation, making it impossible to reference its types directly during runtime.

Link to interactive code sample

Answer №2

It is advisable to utilize generics over traditional type arguments in this scenario. Generics have a unique syntax when compared to JavaScript emitted arguments. Here is an example:

type MyType = |
  { name: string } |
  { age: number };
const processType = <T extends MyType>(item: T) => {
    return { ...item };
};

const outcome = processType({ name: 'Alice' });

As a result, the variable outcome, which is a new object generated within the function, will be correctly typed as { name: string }.

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

Definitions for TypeScript related to the restivus.d.ts file

If you're looking for the TypeScript definition I mentioned, you can find it here. I've been working with a Meteor package called restivus. When using it, you simply instantiate the constructor like this: var Api = new Restivus({ useDefaultA ...

Error message in Typescript: When a class has initialized properties, a 'super' call must be the first statement in the constructor

I am currently facing some typescript errors in my project. Would you like to see a sample of the code that is causing the issue? Here is a snippet: module CoreWeb { export class Controller implements IController { public $q; ... This piece of cod ...

Calculate the total by subtracting values, then store and send the data in

Help needed with adding negative numbers in an array. When trying to add or subtract, no value is displayed. The problem seems to arise when using array methods. I am new to arrays, could someone please point out where my code is incorrect? Here is my demo ...

TS7030: In Angular13, ensure that all code paths within the guard and canActivate methods return a value

Having trouble using guards for an unlogged user and constantly facing errors. Error: TS7030 - Not all code paths return a value. Below is my auth.guard.ts file: import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from &a ...

Encountering an ECONNREFUSED error upon upgrading from Next.js 12 to 13

After upgrading from Nextjs 12 to 13, I am experiencing issues where every time I try to run the application, I encounter ECONNREFUSED to my local host but the port seems to keep changing. This results in the application not rendering properly. > <a ...

What is the process for applying cdkDropList to the tbody when using mat-table instead of a traditional HTML table?

I have been experimenting with the mat-table component in my Angular project, following a simple example from the documentation: <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <!--- These columns can be ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...

Setting the default value for ngModel does not receive any information from the model

I am trying to populate a form with default values using the code below: <h3>ِStart Time</h3> <div class="row" > <div class="col"> <label for="startTime">Hour(s) </label> <input type="numb ...

Sorting through items within a container object

I am currently working with an object named 'docs' that contains multiple objects within it. I am attempting to determine the count of entries that have specific values for both 'exopp_rooms_id_c' and 'is_active'. While this m ...

Utilizing TypeScript with Context API

This is my first time working with Typescript to create a context, and I'm struggling to get it functioning properly. Whenever I try to define interfaces and include them in my value prop, I encounter errors that I can't figure out on my own. Spe ...

Having trouble retrieving values from the getEntry method in Contentful

How can I retrieve an entry from contentful using Contentful v10 with Node.js 18? I am having trouble accessing the value in getEntry(). interface Example { contentTypeId: 'item' fields:{ title: EntryFeildTypes.Text rate: EntryFeildType ...

Guide on transforming an array of objects into a fresh array

I currently have this array: const initialData = [ { day: 1, values: [ { name: 'Roger', score: 90, }, { name: 'Kevin', score: 88, }, { name: 'Steve&apo ...

What is the method for deducing the names that have been announced in a related array attribute

In my definitions, I have identified two distinct groups: Tabs and Sections. A section is encompassed by tabs (tabs contain sections). When defining sections, I want the tab names to be automatically populated by the previously declared sibling tabs. But ...

Troubleshooting the need for refreshing in an Angular application when selecting the same menu option repeatedly

Issue with Angular Application: I've noticed a problem in my Angular app where clicking the menu within a component does not trigger a refresh or reload of the component. I want to make sure that the component reloads whenever its specific menu is cl ...

How can we avoid printing out undefined data from an Observable in Angular 2?

Here is the code I have in my service: fetchUserData(userId: string): Observable<any> { return this.http.get('https://jsonplaceholder.typicode.com/todos/' + userId) .map((response: Response) => { const userData = ...

Can the garbage collector in Typescript/JavaScript effectively handle circular references, or does it result in memory leaks?

When working in languages such as C#, managing memory is not a problem. However, this can lead to difficult-to-find memory bugs in other languages. Is it safe to use the following code snippet in Typescript or Javascript without encountering any issues? c ...

Is it considered bad form to utilize nearly identical for loops in two separate instances within Angular 6?

I am working on creating two lists for a roster. The first list will display the current members of this year, while the second list will show if individuals have been excused for this year. After analyzing my code, I realized that I am using two identic ...

The introduction of an underscore alters the accessibility of a variable

When working in Angular, I encountered a scenario where I have two files. In the first file, I declared: private _test: BehaviorSubject<any> = new BehaviorSubject({}); And in the second file, I have the following code: test$: Observable<Object& ...

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

Missing from the TypeScript compilation are Angular5's polyfills.ts and main.ts files

Here is the structure of my Angular5 project. https://i.stack.imgur.com/tmbE7.png Within both tsconfig.app.json and package.json, there is a common section: "include": [ "/src/main.ts", "/src/polyfills.ts" ] Despite trying various solu ...