Questions tagged [typescript-generics]
For questions related specifically to usage of generic types in TypeScript.
3,050
questions
1
vote
0
answers
12
views
How to infer type parameter definitions of a function type in TypeScript?
I'm trying to extend the following Next.js function type:
export type GetStaticProps<
P extends { [key: string]: any } = { [key: string]: any },
Q extends ParsedUrlQuery = ParsedUrlQuery,
D ...
0
votes
0
answers
13
views
Overwriting generic type in method
Let's say I have a base class like this:
class FooClass {
getFoo<FooType extends string | number>(foo: FooType): string {
throw "not implemented";
}
}
And I want to have 2 ...
1
vote
1
answer
24
views
How to type function that takes two arguments of same type
This a follow-up to Using the knowledge that two arguments have the same type.
I have this function which can be called with two argument of the same type from a set of types. The set contains every ...
1
vote
1
answer
36
views
Using Array<keyoff T> as parameter and Partial in generic function
I am trying to create a class and methods that will be used to retrieve data from database.
For instance:
export default abstract class BaseRepository<T> {
public async findEntities(...
0
votes
0
answers
26
views
Index signature for type 'string' is missing in type
type Arg = Record<PropertyKey, unknown>
function foo(d: Arg) {
console.log(d)
}
type M<T, D> = {
type: T,
data: D
}
type MyType1 = M<'bar', {name: string}>
const a1: ...
0
votes
0
answers
10
views
Typescript React forwardRef with Union/Generic Element
I'm trying to implement element that can be div or button element
type customElement = HTMLDivElement | HTMLDivElement .....
const Element = React.forwardRef<customElement, somePropInterface>...
0
votes
0
answers
27
views
How can I improve the creation of a type array based on the real keys of an object?
Is it possible to improve this code and reduce the repetition?
Here is a simple recreation which should show the problem: Playground
As you can see, I have to repeat myself to create the ...
0
votes
0
answers
21
views
generic interface type that returns a concrete interface or a standard interface depends on the value of the "type" field
I have already asked on the TypeScript Discord but did not receive an answer.
My goal is to define a type that TypeScript can derive based on the value of "type". If it can't, it should ...
1
vote
0
answers
38
views
Generic Parent ignores Generic children React
First, here's my "Parent Component" or "Factory", I'm not quite certain what the terminology is.
export interface ReadOnlyProps {
ignoreReadOnly?: boolean;
disabled?: ...
0
votes
0
answers
24
views
Dynamically add fields to type and iterate over them in TypeScript
I'm building a dynamic formatting system and I want to allow "automatic" (by TS) fields definition.
I want to obtain, if possible, something like this:
enum ContentFormat {
Markdown = '...
0
votes
1
answer
44
views
How can I create a type array from an object that contains the keys?
I think for my scenario there must be a better way to avoid duplicate code, but I can't get it to work..
I have an object like this:
const sectionTypes = {
foo: ...,
bar: ...
} as const;
Based on ...
0
votes
0
answers
21
views
TypeScript: construct return object type based on array elements
Let's say I have an array such as
type Element = 'foo' | 'bar' | 'baz'
const els: Array<Permission> = ['foo', 'bar']
I would like to write a generic function that will infer a type such as
{
...
2
votes
1
answer
55
views
How to overwrite arguments of a function type in TypeScript?
I'm working on a Next.js app and this type exist to to defined getStaticProps methods in pages:
export type GetStaticProps<
P extends { [key: string]: any } = { [key: string]: any },
Q extends ...
0
votes
1
answer
32
views
Using the knowledge that two arguments have the same type
I'm learning TypeScript. In this example, I'm trying to write a generic function that I can use to compare either two numbers or two tuples of numbers. I've defined a type alias Compare for the ...
0
votes
0
answers
28
views
Typescript: Creating a coordinates type that takes in dimension as a generic
I want to define a few types that extend arrays with specific lengths. I have fixed length arrays and minimum length arrays:
interface FixedLengthArray<T, L extends number> extends ReadonlyArray&...
2
votes
1
answer
35
views
How to overwrite properties of a type with generics in TypeScript?
I'm building a Next.js app in TypesScript and one of the type is:
type GetStaticPropsContext<Q extends ParsedUrlQuery = ParsedUrlQuery, D extends PreviewData = PreviewData> = {
params?: Q | ...
0
votes
0
answers
23
views
Limit react children to a type of <T>
Is this possible to limit children to a specific type of T with component function ?
Like this (but JSX.element is not a generic...) :
interface IProps {
children: JSX.Element<IMyComponentChild&...
0
votes
1
answer
33
views
Setting a dynamic or conditional value of an interface property in typescript
I'm trying to build a react component which shows a stack images, something like this,
and for that, I'm trying to type it with interface and types to enforce taking some props in a particular way. ...
0
votes
1
answer
22
views
How to initialize a TypeORM Repository based on a Generic Type "T" using getRepository()?
db.ts initializes TypeORM:
import { DataSource } from "typeorm"
import { Student, Teacher } from "core"
export class Database {
public static AppDataSource: DataSource;
...
0
votes
0
answers
23
views
for create result use type from callback
I trying to write one function that will create result type from callback that is passed in his secound call, and use data that passed in third call
function reusable<T>() {
return function<...
1
vote
1
answer
27
views
Creating custom return type for a generic function in TypeScript
I have the following generic function:
function getFoodProperties<T, K extends keyof T>(foods: T[], keys: K[]): any[] { // <-- any needs to be typed according to generic types?
return foods....
0
votes
0
answers
26
views
Optionally wrapped objects created by a factory cannot be assigned generically to a map of such objects
So, I have this pretty complex case I try to solve. Basically, I have these Bags of values of different types. I try to implement a factory, that takes a Definition as an input, then produces a value ...
2
votes
1
answer
36
views
Get return type from a map of generic functions
I have the following dictionary where functions are polymorphic, accept the same argument but return different result:
const dict = {
one: {
foo<A>(a: A) {
return [a] as const
}
...
3
votes
1
answer
27
views
Create a type having the keys from the values of an Object
Given the following type:
type FromValues<T> = T extends Record<infer K, infer V>
? V extends string
? { [Key in keyof V]: string }
: never
: never
I was expecting to get a ...
0
votes
0
answers
29
views
How to set generic type on anonymous function
Is there any way I can make the product in canDisplayConditions also generic?
export interface ViewModel {
canDisplayConditions$: Observable<(_arg: {
product: T; <-- to generic type
}) =&...
0
votes
0
answers
32
views
in typescript, how to define an object which method is generic function
type T0<T> = {
a: T
}
type T1<T> = {
onStart(params: T0<T>, context: string): Promise<void>;
}
function onStart(params: { a: number }, context: string) {
return ...
1
vote
1
answer
25
views
Convert list of properties to property tuple
This question is similar to this one, but I think it lacks a lot of the main caveats and concerns raising issues there because I'm not making any assumptions that the properties of a given interface ...
-1
votes
0
answers
44
views
Multiple inheritance in Angular (Typescript)
I have several pairs of services in Angular (TS), one pair is: XStateRestorerService and XStateResetService for example, which extend abstract services: AbstractStateRestorerService and ...
3
votes
3
answers
56
views
Infer a type within a type from an object
type operation = 'create' | 'update' | 'delete';
type mutationKey = {
operation: operation;
id: K extends 'delete' | 'update' ? string : undefined; // want this field to be undefined if operation ...
0
votes
1
answer
17
views
Generic to check if parameter types of object are equal
I'm trying to write an update function that takes a target object a and it needs to update the key aKey with the value of another object b, with its own key bKey.
I tried using this code:
const ...
0
votes
0
answers
23
views
How to extend these events in typescript
Consider the code below, which shows an event listener implementation.
It works great, though I would like for the event type to be extended, so consumers can create their own events.
export enum ...
0
votes
3
answers
25
views
React Typescript discriminated union gives compiling error but works on IDE
I have a component that has 2 properties. It may or may not accept one of those (say prop b), but you always need to pass the prop a. If the b prop is passed, it should change the typings of a.
...
-1
votes
1
answer
20
views
Typescript generic extend typeof JSON
I have a JSON:
{
"menus": {
"main": {
"title": "Foo",
"buttons": {
"chooseSphere": "Btn #1",
&...
-1
votes
0
answers
20
views
How to make an abstract factory class in Typescript?
I have read related threads, but I have not found a solution for my use case.
I have an abstract class Store, that allow me to generate a sub class on the fly. Each subclass has a proper interface.
...
0
votes
0
answers
35
views
Typescript provide default generic type in another function
I made a wrapper function to execute sql statements and that function takes in a generic type to determine the return type. I wanted to make another wrapper function that provides a default type to my ...
0
votes
0
answers
22
views
Extending a dynamic object without loosing access to literal keys
I want to have an object that has an initial set of keys that is extendable by the library user through a function. How would I archieve this without loosing access to the union of all valid keys? ...
0
votes
0
answers
43
views
TypeScript smart generic
I don't even know how to google this question, so I'm not sure what the best explanation for it would be. Let me just show an example.
Let's say that I have a type like this:
type SomeType<Prop, ...
4
votes
1
answer
109
views
Typescript - Property does not exist on extended generic interface
Scenario: I am attempting to create a base method I can reuse (works/doesNotWork) for a few different calls I need to make. The base method should do some setup as I do not want to repeat several ...
1
vote
0
answers
37
views
Typescript generic for function that can receive multiple array of functions for pipe
I have function that can receive object that have multiple arrays of functions that will using like functions for pipe
I find generic that can validate that functions in pipe have compatible types but ...
1
vote
1
answer
33
views
Set object to intial value by looping through keys
I have an object that I want to allow to be reset. The type of mockData[key] and cloneDeep(initialState[key]) seems to be Todo | User, so I'm not sure where the intersection in the error is coming ...
0
votes
1
answer
29
views
value pass in react component props as typescript types for other props
I'm trying to read value passed to the prop of my react component, and read it as type for other props in the same component
const TestPage = () => {
return (
<Test
tabs={[
{ ...
0
votes
1
answer
46
views
How to type a closure?
Todos.tsx
import React, {useState, useCallback} from "react";
import {TransitionGroup, CSSTransition} from "react-transition-group";
import {v4 as uuid} from "uuid";
...
2
votes
2
answers
53
views
React generic useFetch state
I'm trying to write a custom hook useFetch that makes many requests for different data.
The problem is that I can't typing my date correctly, I have state like this.
interface IState<T> {
...
2
votes
2
answers
60
views
Infer type of parameter based on a previous parameter
Let's assume that in my codebase I have two different implementations of an EventEmitter.
For example something like this:
type HandlerA = (data: boolean) => void;
type HandlerB = (data: number) =&...
1
vote
1
answer
23
views
How a generic void type can make an arg optional in typescript
I'm trying to create a class that returns an instance that receives an argument with generic type, and sometimes this argument may not exist, I don't want to leave the possibly undefined, so I thought ...
1
vote
1
answer
50
views
TypeScript - creating child class instance inside parent class
Please take a look at the following example:
type Task = (input: number) => number;
abstract class ParentClass {
constructor(protected tasks: Task[] = []) {}
protected abstract ...
1
vote
1
answer
49
views
How to Infer the Return Value of Another Method From the Type Argument Given to the Constructor’s Argument
The return value of the following Resolver.prototype.resolve() method is Model<unkown>.
The types I am expecting are Model<{ x: number, y: number }> and Model<{ name: string }>.
Also,...
1
vote
1
answer
42
views
Typescript generic associative array
I would like to get deep value from the object, for example result when generic is "books":
fieldName: {author: "", langauge: "", translation: ""}
export const ...
1
vote
2
answers
43
views
Typescript Generic Function Interface in another interface
I have a generic interface
export interface Method<T> {
(answer: T): T;
}
I want to create an interface where I have fn function
interface Wrapper {
fn: <T,>(a: T ) => T
}
but ...
-1
votes
0
answers
26
views
Can I express in typescript <T extends string except "this-specific-string">? [duplicate]
I'm basically asking, because I'm trying to do this:
type MemCache = {
id: string
[key: string]: MemCacheValue
}
But TS doesn't like that. If there's a way to restrict key to any string except id ...