Questions tagged [typescript-generics]
For questions related specifically to usage of generic types in TypeScript.
4,434
questions
0
votes
1
answer
25
views
Is it possible to have tyepscript infer generic types from a zod schema passed into a function
I have a pattern to statically type-check endpoint calls in my typescript application, using zod schemas to ensure correctness at runtime. My solution, using generics, works but I have to manually ...
0
votes
2
answers
73
views
Typescript: Generic function for creating a lookup object
I currently have a function to which I can pass an array of objects, where the objects all have the _id key. From that object the function creates a lookup object, which has the _id fields as keys and ...
1
vote
2
answers
48
views
How to extend Array to enforce specific arguments in TypeScript?
I'm using TypeScript and I want to extend Array to enforce a specific argument. This way, I can make sure that whenever I create a FruitArray, the first element is a fruit.
So I tried extending Array ...
0
votes
0
answers
11
views
Designing Generic Type Dropdown/Bottom Drawer component
this is the first time I've run into an issue like this as I don't often use generics and was looking for some advice.
We have an existing Dropdown component in our codebase that takes in the ...
1
vote
2
answers
65
views
How to find a matching object in two generic arrays by attribute name?
I have a generic abstract class which contains two generic arrays:
export abstract class DataProvider<V, T extends {token:string}> {
inputA: T[] = [];
result: V[] = [];
}
I want to provide ...
1
vote
1
answer
45
views
Assert super type as a generic parameter in TypeScript
The Question
In TypeScript we can use extends to assert a generic parameter as a 'subtype' of another type. E.g.
// class Base {}
// class Child extends Base {}
// edited:
class Base { a = 1 }
class ...
1
vote
1
answer
49
views
Typescript Type Guard in callback function return incorect type guard (return guard type with additional undefined type)
I wrote a filterObject function that accept an object and a callback function as input the function. For the callback function, I described the Type and a type guard. But for some reason, the type ...
0
votes
1
answer
52
views
How to use typescript in reduce function
My code:
const calculateSum = <T>(array: T[], key: string): number => {
const total = array.reduce<number>((accumulator, object: T) => {
return accumulator + object[key];
}, ...
1
vote
0
answers
33
views
How to call an instance method that calls another instance method, while preserving the instance type?
We have a base class, and then some derived classes that extend the base class. We want to define an instance method that is strongly-typed such that it accepts only the name of another instance ...
1
vote
1
answer
35
views
Extend generic type in abstract class property definition
We have multiple pages with data grids, sharing basic functionality -> paging, sorting, export. In order to simplify them and speed up the development, I want to create the BaseGrid abstract ...
1
vote
0
answers
17
views
what's the difference between `type FooFn <Bar> = (bar: Bar) => any` and `type FooFn = <Bar> (bar: Bar) => any` [duplicate]
Just like in the Q's topic;
what's the difference between type FooFn <Bar> = (bar: Bar) => any and type FooFn = <Bar> (bar: Bar) => any.
Obviously, 1st snipped requires the use of ...
0
votes
2
answers
82
views
How to define the type of a property based on one of the types in the same object
I have a React Component that takes up an object which returns the input component to be rendered. But right now there is no strict type checking and that is the problem. Check the example below:
...
2
votes
2
answers
142
views
How to define a typescript function with a generic function parameter
I want to pass a 'generic' function as parameter to a function without 'specialising' the function at that time. Something like:
type F<T> = (p: T) => void
function report(f: F) {
f<A&...
1
vote
2
answers
45
views
Is there a way to pass an array of generic types so that the generic type of each element is inferred?
Consider the following:
type ValueMap = {
foo: 'FOO1' | 'FOO2';
bar: 'BAR1' | 'BAR2' | 'BAR3';
};
type Key = keyof ValueMap;
type Value<K extends Key> = ValueMap[K];
type ...
0
votes
0
answers
22
views
Holding a type in a member or return a type from function in Typescript
I'm trying to create a central Events class for my entire events in the system, so developers will just need to navigate over this class to look for the relevant events. my queue messages handlers are ...
0
votes
2
answers
30
views
Typescript Generics: How to restrict key of record to be string?
Typescript here complains:
Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'.
type TableProps<Row extends Record<string, ...
1
vote
1
answer
102
views
Declare interface that respect mapped type
On a typescript project, I have created the following mapped type GlanceOsComparatorV2
interface DonutData {
label: string;
value: number;
}
interface ProjectMetric {
value: number;
}
enum ...
0
votes
1
answer
57
views
How to return a class type with a generic in it from Typescript?
I have an object with a specific key and a value with an array of strings.
const experimentPossibleVariants = {
'experimentOne': ['experimentOne - A', 'experimentOne - B', 'experimentOne - C'],
...
2
votes
1
answer
27
views
How to define such a TypeScript generic that traversal the routes config tree and accumulate path
I have
type Route = {
path: string
children?: readonly Route[]
}
const root = {
path: "a",
children: [
{ path: "b" },
{ path: "c", children: [{ path: &...
0
votes
0
answers
17
views
TypeScript: Is it possible to get Union Type of Array<keyof CustomObject> only containing the present keys?
I want to create a function which uses a generic type to describe a object and accepts an array of Keys of the generic type. The function returns a function which accepts a object of the generic type ...
0
votes
2
answers
39
views
Can an input array be used to determine the keys on a returned object?
I want to create a function that takes an array of possible string values and returns an object that has keys that match the values of the input array. The values of the object properties will be ...
1
vote
1
answer
23
views
Typescript Generics: Inferring Generics in sub levels
I have several types that I am working with that I would like to have inferred at the method call level.
class AbstractModal<TInput, TOutput> {
...
}
type Constructor<T> = new(...args: ...
0
votes
0
answers
17
views
show options depending on the key given in the object
Can't get typescript to show options depending on the key given in the object.
in TInspectorConfig I want the type type to reflect on the options type.
export type FormControlOptions = {
input: {
...
0
votes
1
answer
54
views
Typescript generic with generic key with string value
I have the following interface structure
interface Table<T> {
data: T[];
tableConfig: TableConfig<T>;
}
interface TableConfig<T> {
fieldNames: Array<keyof T>;
...
2
votes
1
answer
73
views
Why doesn't TS evaluate my type parameter to its full extent and how can I work around this?
I have a generic type that is a little complex, including a union where one of the elements is only allowed if the undefined extends the type parameter T.
type PropValidator<T> = {
[k in keyof ...
0
votes
0
answers
33
views
How to handle multiple related lists of generics in typescript
I have a list of objects typed as GenericType, and T is different for each object.
I also have another list of keys of T (same size as first list).
I would like to map both lists, relate them. I could ...
2
votes
1
answer
27
views
How to properly type a table of tuples to array of objects utility function (like zip) avoiding merged union of all values in typescript 5.2.2
I'm close to nailing it, but can't find a way around the final TS2322: Type TcolTuple[i] is not assignable to type string | number | symbol compiler error.
So, here is a utility function ...
0
votes
0
answers
30
views
Omit props from type that was already passed via different variable
function useStuff<T>(props: Partial<T>) {
const open = (addProps: Omit<T, keyof typeof props>) => {
console.info(addProps);
};
return {open};
}
function App() ...
0
votes
0
answers
25
views
TypeScript/JSDoc generics for class prototype as property of another class
I have a class with a method that creates an instance of a configured prototype:
class A {}
class B {}
/**
* @typedef {Object} Options
* @property {typeof A|typeof B} type
*/
class Foo {
/**
...
0
votes
2
answers
33
views
How can I use the classic Omit functionality applied to an array type instead of a type in typescript?
How can I use the classic Omit functionality applied to an array type instead of a type?
For example, I've the following type
type Car = {
a: number,
b: string,
c: Record<string, unknown> |...
0
votes
0
answers
60
views
How to overwrite generic class argument that extends record?
I have a Parent and Child classes. The Parent class takes 2 generic arguments: Result and ParentBuilderMap. Result is expected to be some sort of class, while ParentBuilderMap is a subset of Result ...
1
vote
1
answer
43
views
Extract property type from a oneof
I've got a type a such:
type OneOf =
| {
$case: 'one';
one: One;
}
| {
$case: 'two';
two: Two;
}
| {
$case: 'three';
three: Three;
};
I want to ...
0
votes
1
answer
61
views
Problem with different types depends on boolean value
It's my first post on stackoverflow so I'm asking for understand.
type InputProps =
| ({
isTextArea: false;
label: string;
} & React.ComponentPropsWithoutRef<'input'>)...
1
vote
0
answers
35
views
Why is typed function definition not strickly checking return of function? [duplicate]
I am trying to get property typed function based on generated schema from OpenAPI and I have encountered weird type-checking behavior.
I have following object (simplified for showcasing) where route '...
3
votes
1
answer
48
views
Get child type in abstract class constructor
I have an abstract class that will take any data passed into the constructor and assign it to the instance. The goal being that you can initialize an instance with a subset of its data.
The problem I'...
1
vote
0
answers
27
views
Overriding an abstract getter after a TypeScript Mixin
I have an app using some generic classes with the Mixin pattern, and am trying to implement a property getter that's the same for 90% of users of the mixin, but not quite all...
I was surprised to ...
0
votes
0
answers
13
views
How can I enforce a signature of a React component being passed in to another React component in Typescript?
This code I have is working quite well, the wrapping component naturally inherits all the properties of the component passed in, and is known to the editor when invoking the WrappingComponent. So, now ...
1
vote
0
answers
30
views
Can I create a function in TypeScript that accepts any function and returns a function with the same type signature?
I want to know if it's possible to create a function in TypeScript that takes any other function as an argument, and returns a new function with a modified type signature that can be called in the ...
1
vote
1
answer
26
views
How to use polymorphism to transform an object from one type into another with "transformer" classes inheritance
I'm developing a GraphQL API. The GraphQL types and the database types are not the same because I didn't want my database specific structure to leak to the API consumers. Basically I want to rename ...
1
vote
1
answer
27
views
How do I set an arg of a generic type using React's useState hook?
I'm building a form component that takes a callback that accepts an arg of a generic type, but I'm running into some difficulty when I try to update the arg in the form:
Here's how I'm calling the ...
0
votes
0
answers
47
views
Argument of type 'Type1Model | Type2Model' is not assignable to parameter of type 'Type1Model & Type2Model'
im using a library in a reactjs using typescript, this library exposes some types (lets say the types are the following) :
//----------- I DON'T HAVE CONTROL OVER THESE (edited)
type Type1Model = { ...
1
vote
1
answer
36
views
TypeScript: Create a new type from a nested object values
I'm trying to create a new type from nested object value but if the key is not present
on any of the nested levels, it is failing, Where I'm going wrong?
const events = [
{ name: 'foo' },
{ name: ...
0
votes
0
answers
19
views
TypeScript: Why type conditions behave differently in generic types? [duplicate]
In TypeScript, I'd assume that
type X = A extends B ? true : false
Would be equal to:
type Check<P, Q> = P extends Q ? true : false
type Y = Check<A, B>
But as it turns out, it is not. ...
0
votes
1
answer
56
views
How to Determine the Return Type of a Generic Function? Function Return Types are different objects
I have a function fn, I want this function to return the appropriate object type based on the typename parameter, but I don't have access to the types A and B.
For example, if the function is called ...
2
votes
0
answers
27
views
Field's type base on it parent's type
I'm facing the following problem in Typescript:
class PopulationDto<E> {
path: keyof E;
population?: PopulationDto<any>[];
}
class Building {
floor: string;
room: string;
}
...
0
votes
2
answers
25
views
Generic Function to fill a attribute of object
I'm creating a method setParameter in class Manager that should allow to user to fill out Object of type Settings.
After every update of settings I have to redraw scene.
The code I have now:
class ...
2
votes
3
answers
59
views
TypeScript cannot index type over generic reference
Why is the following type code invalid?
interface T0 {
key1: string
key2: string
}
type T1 = {
[v in keyof T0]: string
}
type T2<T extends T1> = {
[k in keyof T]: T0[k]
}
I get an ...
0
votes
0
answers
34
views
i need to create a reusable classes for the controllers and services in Nestjs & typeorm
i created abstract class for the BaseController and BaseService with passing a dynamic permissions to each method, my problem is the DTo , how can i pass a dynamic Dto to each method ??
do u think it'...
1
vote
1
answer
42
views
Typescript - Dynamic types
I am trying to type this example => typescript playground
const obj = {
func1: ({ a }: { a: string }) => { console.log(a) },
func2: ({ b }: { b: number }) => { console.log(b) },
}
...
0
votes
0
answers
87
views
Generic typing of callback functions in classes
This is a follow up from my last post Generic types in classes which has been perfectly answered by @jcalz. Since playing around with this solution, I highly doubt my understanding of Typescript in ...