Questions tagged [type-inference]

Type inference is the process of inferring types for programs automatically, using rules defined by a type system.

Filter by
Sorted by
Tagged with
0 votes
1 answer
43 views

Type inference in generic structs in Go

Consider the following code import "fmt" type key1 int type key2 string type value int type m1 map[key1]value type m2 map[key2]value type A[key key1 | key2, t ~map[key]value] struct { ...
Remi.b's user avatar
  • 17.5k
0 votes
0 answers
26 views

How can I narrow down a value in a function that takes in a key and a value

I'm trying to create a function which can take a key of a type and a value corresponding to that key. Then I want to do something when I'm looking at a specific key. My specific use case for this is a ...
Sebino Hoo's user avatar
0 votes
0 answers
32 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 ...
Lucas's user avatar
  • 27
0 votes
1 answer
42 views

How to configure Typescript to infer discriminated unions when `is` and `never` is present?

I had a library in my project that I stopped using (deleted from package.json), and one of its peer dependencies was fp-ts, so I had to add fp-ts to my project. fp-ts has an Either type which can be ...
Adam Arold's user avatar
  • 29.5k
-1 votes
1 answer
42 views

How to define classes for several computation steps to use Type inference in Java?

How to change the code below to get type inference? The line Integer b = run().task1(()->555).task2((a)->a+5); Does not compile, because compiler can't conclude that a is Integer. class MyTest ...
Pavel Bernshtam's user avatar
1 vote
1 answer
56 views

Telling Haskell compiler that two types are compatible

I've got the following Haskell function: apply_to_f :: (a -> a) -> ((a -> a) -> b) -> ((b -> c) -> c) apply_to_f f = \ g -> \ h -> h (g f) (This comes from the 'pred' ...
Theo H's user avatar
  • 143
0 votes
0 answers
37 views

Why does the scope of a type matter when inferring generics from decorators in TypeScript v5+?

Let's say you have a decorator factory function which returns a decorator to be put on class fields and which adds metadata for validating the field as an email: // email.ts export type ...
BrunoT's user avatar
  • 424
1 vote
1 answer
75 views

Java nested generics with raw types return type inference

public class Main { List<List<Integer>> f0() { return List.of(List.of(1L)); } List<List<Integer>> f1() { return List.of((List) List.of(1L)); } ...
ParSal's user avatar
  • 130
0 votes
1 answer
22 views

Object property won't infer union type created from keyof typeof computed properties

If I create a union type from the keys of an object, I can pass that type around perfectly, as long as the keys are regular strings. But if I use computed properties as keys for the object, ...
ShaneSauce's user avatar
1 vote
0 answers
37 views

Infer the Values of a TypeScript Enum at the Type Level [duplicate]

I am trying to create a generic type called EnumValues that accepts an enum instance as a parameter and outputs the type for the values of the enum. The solution should be such that specific enum ...
Eliya Cohen's user avatar
  • 10.9k
1 vote
1 answer
93 views

How to transform object field name using type infer in Typescript?

I've implemented a parser builder with transformed object key (it works in js) but having difficulty to transform the inferred type of object key. Sample Code: let sampleData = { id: 1, ...
Beeno Tung's user avatar
  • 1,080
0 votes
1 answer
20 views

TypeScript sets type 'never' for resolved value after Promise.allSettled().forEach() processing

TypeScript is giving me a type 'never' after a Promise.allSettled(promises).forEach(results)? type myValue = { test1: string; test2: string; test3: string; } | undefined; ...
hcbd's user avatar
  • 3
1 vote
1 answer
53 views

Why does Comparator.thenComparing() work when storing the comparators in variables but not when inlineing them? [duplicate]

I have two comparators which I chain using thenCompare(): Comparator<Edge> byAX = Comparator.comparing(e -> e.a.x()); Comparator<Edge> byBX = Comparator.comparing(e -> e.b.x()); ...
Aaronmacaron's user avatar
1 vote
0 answers
72 views

Infer type for the interface field from the return type of another field [duplicate]

I would like to have a types for defining configuration for sorting. These are the types I have described: export type SortConfig<T> = ReadonlyArray<SortItemConfig<T>>; export ...
Andrei Khotko's user avatar
2 votes
1 answer
52 views

Design deprecation warning to replace a list with vararg

I have the following methods: fun RowVector(x: Double, y: Double): RowVector2 = RowVector(listOf(x, y)) as RowVector2 fun RowVector(x: Double, y: Double, z: Double): RowVector3 = RowVector(listOf(x, y,...
vatbub's user avatar
  • 2,809
1 vote
1 answer
40 views

Issue with type inference in function overloading in TypeScript

Why the following example fails to compile? function mapObjectValues<I, O, K extends keyof any>(obj: Record<K, I>, map: (value: I, key: K) => O): Record<K, O> function ...
TN.'s user avatar
  • 18.9k
1 vote
1 answer
32 views

Complex generic async return type fails to infer specific return values

In this playground, I am trying to make a generalized API handler helper that ensures common response types and also leverages inference so that our application code can exhaustively handle all ...
osdiab's user avatar
  • 2,012
2 votes
1 answer
45 views

How to narrow TypeScript discriminated unions based on partially known discriminators?

I'm working on a React hook for abstracting state for various features that share some function arguments, but where certain feature-specific arguments should be required/disallowed based on which ...
Mike Turley's user avatar
3 votes
1 answer
37 views

My type predicate function does not work as I would expect. Need help understanding why

Consider the following type predicate function to check if an object contains a specific key: export function objectHasKey<T extends object>( obj: T, key: PropertyKey, ...
Thijmen's user avatar
  • 406
0 votes
1 answer
23 views

How to infer type from property of items of Array-property

I have a type like this: type Person = { name: string; relatives: Array<Person>; favoriteRelative: string; } But I want to enforce favoriteRelative to be a name from any Person in ...
rippster's user avatar
0 votes
1 answer
32 views

Understanding TypeScript Type System: Issue with Generated Arrays and Const Assertions

I believe I'm facing a fundamental understanding issue with TypeScript, as evidenced by the behavior in the following code snippet. I'm trying to understand why a generated array isn't working and if ...
Friedrich Siever's user avatar
1 vote
2 answers
40 views

typescript how do i infer from mapping type

Hi I create a plugin and a function to callPlugin action. export class Plugin { actions = { 'join': ({ groupId }: { groupId: string }) => { }, 'addPoint': ({ point }: {...
Mr.Trieu's user avatar
  • 436
0 votes
0 answers
39 views

Rust cannot infer type in closure

Consider the following code: fn main() { let v: Vec<f32> = vec![0.0]; let foo_a: f32 = (|i| v[i])(0); // This works let v: Vec<(f32, f32)> = vec![(0.0, 0.0)]; let foo_b: ...
Roy Varon's user avatar
  • 556
0 votes
0 answers
25 views

Infer function argument type inside object literal in TypeScript

Given the code below: type State<T> = { [K in keyof T]: T[K] extends (state: infer A) => infer R ? R : T[K]; }; type StateDef<T> = { [K in keyof T]: T[K] extends (state: infer A) =&...
rarrosi's user avatar
0 votes
1 answer
44 views

How to infer and save a type from an array of objects?

There is this very messy API I want to consume, where the values returned are somewhat inconsistent. I could go over every single entry and try and make a type that would cover it, but this would take ...
Pedro Dalla's user avatar
0 votes
1 answer
88 views

Trying to deep merge on type level

I have a JavaScript mergeDeep function that recursively merges objects and arrays. It works as expected in terms of functionality, but I want to improve it by ensuring that the return type of the ...
stambolievv's user avatar
0 votes
0 answers
67 views

How can I used Fairseq model in inference mode?

I've build a speech to text translation model using Fairseq library. Now I want to use it in inference mode without using fairseq-generate commandline. How can I process ? thanks in advance
Wabbina's user avatar
  • 15
0 votes
1 answer
42 views

Dynamic return type based on array of keys inputted to function

I have x number of modules that are used in my AWS lambda functions such as a UserModule, NotificationsModule, CompanyModule, etc. I created an interface that describes the structure of the modules as ...
Ben Young's user avatar
4 votes
1 answer
81 views

Why is Typescript not correctly inferring the type of an array’s element?

I have an object, RollingStockSelectorParams that contains arrays. I’m trying to get TypeScript to infer the type of elements of the choosen array additionalRsParams[title] Primary question: why is ...
Albizia's user avatar
  • 569
2 votes
0 answers
34 views

Can context sensitive inference be "pushed up" chained method invocations?

I'm trying to build a Zod-ish API, but with type inference of values instead of the z.string()-is-definitely a string, i.e. I want to do something like: // Create a Zod-style fluent DSL for building ...
Stephen Haberman's user avatar
1 vote
1 answer
32 views

Type inference with a Union types when accessing object by key/square brackets

I have a union type that is set in an object array type where I am dynamically looping after and using. When I set the object as a variable, check with an if case its type and then access it, the type ...
yusuf's user avatar
  • 11
0 votes
1 answer
106 views

Structural directive - ngTemplateContextGuard not working

I've built a datatable compoonent where I'm using a structural directive to pass a rowTemplate: <bs-datatable [data]="artists"> <tr *bsRowTemplate="let artist"> &...
Pieterjan's user avatar
  • 2,880
0 votes
0 answers
51 views

mypy infers unexpected Arg in python type signature

I am currently introducing type hints into a project I am currently working at. To check the type signatures, I am using the mypy type checker. When using the map function, I am getting unexpected ...
D. A.'s user avatar
  • 33
0 votes
1 answer
25 views

Infer property type given property key using Typescript

I'm wondering how to go about inferring a property type given a property key. I'm not sure if this terminology is accurate, so I'll describe using an example (if I'm using the wrong or confusing ...
devklick's user avatar
  • 2,237
2 votes
1 answer
36 views

Is it possible to exclude "this" from Type Inference in TypeScript?

I have the code below as a generic function to get all parents in a Tree type of structure. When I use it in a class though, I'm getting a Type Error. type GetParentFunc<T> = (x:T)=>T; ...
Dirk Boer's user avatar
  • 8,684
0 votes
1 answer
91 views

Rust trait method with default implementation self type is not what is expected

So I have this FileSystem trait in rust pub trait FileSystem: Debug + Send + Sync And in that trait I have this method here with a default implementation: fn location_with_sub_path(&self, ...
James Gaunt's user avatar
0 votes
1 answer
23 views

Is there a way to make it a type inference of an array imported as a splice function from different types of tuples?

For example, let's say there's a code below. type MyType = 'a' | 'b' | 'c'; const a = [3, 5, 'a', 'b'] as const; const func = (arg: readonly [number, number, ...MyType[]]) => { const ...
dom wis's user avatar
  • 27
1 vote
1 answer
34 views

Is there a way to match the type to the "key" change?

For example, I wrote the following code. func({ items: [ { event: 'a', callback: (data) => { }, }, { event: 'b', callback: (data) => { }, }...
dom wis's user avatar
  • 27
0 votes
1 answer
96 views

TypeScript convert tuple type with nullable type to tuple with non-nullable type

I am going to function to memoize return values from the function given. const memoize = (value, onHandle) => { for (let index = 0; index < value.length; index++) { if (value[index] === ...
QuavoHuncho's user avatar
2 votes
1 answer
33 views

Extract the first token from an "or list" (union) in Typescript [duplicate]

I want a generic type like below F that if: type X = F<'a'|'b'|'c'> then X should be 'a'. And if type X = F<'alpha'|'beta'|'gamma'|'delta'> then X should be 'alpha'. The below way doesn'...
Mir-Ismaili's user avatar
  • 14.5k
0 votes
1 answer
20 views

typescript deep keyof when field is an option

I create an function to select and keyof of deep object. but I don't know why this keyof on my object is not work when it is an option. type Database = { User?: { id: string name: ...
Mr.Trieu's user avatar
  • 436
0 votes
0 answers
42 views

How to convert union type of strings to union type of objects?

I'm finding a way to convert union of strings type Letters = 'a'|'b'|'c'|'d'; to union of objects. type ObjectsMadeOfLetters = { prop: 'a' }|{ prop: 'b'}|{ prop: 'c' }|{ prop: 'd' }; Does anybody ...
rusanovski's user avatar
1 vote
1 answer
61 views

TypeScript inference not working with optional property

I have created a simple example which describes my problem in general and shows the error: example in TypeScript Playground. type OptionalData<T> = T extends undefined ? {} : { data: T } type ...
user2964559's user avatar
1 vote
1 answer
37 views

typescript how do i infer params of constructor to default class type?

I want a function of class can use a type from arguments of constructor but i don't know how to do that class Foo<T1, T2=any>{ // if i set T2=any i will lose the type a: string = 'a' ...
Mr.Trieu's user avatar
  • 436
0 votes
1 answer
49 views

Why doesn't TypeScript narrow based on checks using a variable key?

If I have code roughly like this: const obj: Record<string, SomeType>; if ("key" in obj) { const val: SomeType = obj["key"]; void val; } the TypeScript compiler doesn't ...
natevw's user avatar
  • 17.1k
1 vote
1 answer
86 views

How to infer generic T in return type through a type guard and implicit inference in lower levels?

type Entity<T> = {payload: T}; interface IBaseDataType {name?: string}; interface IDataTypeV1 extends IBaseDataType {id: number}; interface IDataTypeV2 extends IBaseDataType {id: string}; ...
Nikolai's user avatar
  • 575
0 votes
1 answer
36 views

Typescript type inference - Object key seen as unknown

I want to make type inference from a props object given to a component then passed to a render. Object keys are correctly retrieved but all type are typed as unknown. Need help to understand what's ...
Georgio's user avatar
  • 97
3 votes
1 answer
78 views

TypeScript readonly Array property assignment error

I have a question about TypeScript type inference. Here is a simple example. interface Student { readonly ids: number[], } const ids: readonly number[] = [1, 2, 3]; let student: Student = { ids: ids ...
Jerry Yuan's user avatar
1 vote
1 answer
43 views

Typescript, Type-Inferance: How to make Typescript be able to suggest the name of the props of an object?

Using RTK-query in React we've got a nice feature. Once we've defined the ApiSlice with it's endpoints RTK-query autogenerate hooks for us. Not only that, but Typescript is able to suggest what hooks ...
Emiliano Morghen's user avatar
0 votes
0 answers
42 views

Why does tuple deconstruction return nullable types in C#?

Consider the following C# code: var info = ("A", "B"); if (info is var (a, b)) { Console.WriteLine("X = {0}", a); } For some reason, the type of the a variable is ...
Impworks's user avatar
  • 2,677

1
2 3 4 5
54