Questions tagged [union-types]
This is a tag to discuss the Union Type feature as seen in languages such as TypeScript, Ceylon or F#.
271
questions
0
votes
0answers
18 views
Typescript using enum as literal type in union
I'd like to create a type that changes depending on the value of a member. Union types to the rescue:
type SomeType = {
method: 1,
} | {
method: 2 | 3,
someAdditionalData: number,
}
This works ...
0
votes
2answers
40 views
How to only check true/false value for boolean or undefined union type in typescript?
I have two boolean | undefined variables
const condition1: boolean | undefined = xxx; // xxx is a return value from another method
const condition2: boolean | undefined = xxx;
I want to get the ...
0
votes
1answer
15 views
Calling a function from a map of union types
I have a mapping for a discriminated union from a type of the union to a function using a member of the union as a parameter:
export interface Truncate {
type: 'truncate'
maxLength: number
}
...
0
votes
1answer
24 views
keyof Model not assignable to union of keys issue in generic type
I tried to make strictly typed column builder and ran into union type issue. I think the solution is to infer builder return type as (ColumnDef<Model, "Key1"> | ColumnDef<Model, &...
0
votes
1answer
44 views
Prod build issue while checking the length of union type variable having array type in angular html template
I am facing an issue while checking the length of union type array, string and number. Sample code of issue while build angular project in prod mode:
Variable in ts
public developerData: {
[key: ...
1
vote
1answer
51 views
How to extract “path expression” from an interface in TypeScript?
What I want to achieve is this:
type Post = {
id: number
title: string
author: {
name: string
}
comments: {
text: string
}[]
}
type ExtractPathExpressions<T> = ???
type ...
0
votes
0answers
30 views
Discriminated union and redefining property type
I'm having a following issue in typescript 3.9.7. Given the following code:
type A = {
type: string;
cellRendererParams: any;
filter: string;
};
type C = {
type: 'yy';
cellRendererParams: ...
4
votes
1answer
54 views
How to narrow TypeScript union type with generics
I have a generic function to update state (use-case is dynamically handling updates to tables in React), and have used generics to ensure calling the function is type-safe, but I don't understand why ...
1
vote
0answers
58 views
Distinguish union type with type parameter in Scala 3
In Scala 3, given such a type alias:
type Test[A] = A | Option[A]
val first: Test[String] = "gandalf"
val second: Test[String] = None
val third: Test[String] = Some("sam")
how ...
1
vote
1answer
51 views
Union generic type without Either Scala
This works fine:
def echo[A, B](a: A, b: B): A = ???
This is also fine:
def echo[A, B](a: A, b: B): B = ???
However, how do we achieve this to return either type A or B?
// error
def echo[A, B](a: A,...
0
votes
1answer
23 views
Union type of “keyof” and “string” with working autocompletion
I want to expose a method that takes some Union type as parameter and provides autocompletion for that. As this union type could be extended via declaration merging, autocompletion is a key feature ...
1
vote
1answer
27 views
How to properly use extends instances in TypeScript?
I use TypeScript, but there is still a lot of confusion.
I created an instance like this:
interface Product {
type: 'free'|'pay';
price?: number;
}
The reason I set price as an optional property ...
3
votes
1answer
117 views
How to define a true logical OR of object types (no mixing of different object keys in result) [duplicate]
An example:
type TA = {a:number,b:number}
type TB = {a:number,c:number,d:number}
const t1:Or<TA,TB> = {a:1,b:1} // want
const t2:Or<TA,TB> = {a:1,c:1,d:1} // want
const t3:Or<TA,TB> ...
2
votes
1answer
30 views
Overloaded method of an interface cannot accept a union type: “No overload matches this call”
I use a 3rd party library that defines an interface (A) with an overloaded method (method). The method can accept either null or string value as a parameter.
I define a union type: string | null and ...
0
votes
0answers
28 views
Confusion about TypeScript Union Types
I want a certain property of an object (groupItems) to be either an array of strings or an array of objects so I created the below interface:
interface PanelItem {
groupTitle: string;
...
2
votes
1answer
71 views
How do I modify the Ada record type to be a union type supporting two variants?
The program contains some type definitions that can be used in a
program for playing noughts and crosses (also known as tic-tac-toe). gamePos2 describes a completed position where one player has won
I ...
2
votes
1answer
53 views
Error trying to access the error property of AVPlaybackStatus
I'm new to TypeScript and am trying to work with expo-av for audio playback.
The following code gives me an error: TS2339: Property 'error' does not exist on type 'AVPlaybackStatus'.
const { sound, ...
0
votes
1answer
91 views
Typescript Dynamically Check if value is of a Union Type
I have generated a Union type of my supported methods and I want to check that the method is one of my supported methods and then dynamically call the method.
I know that I can check this by using an ...
1
vote
4answers
111 views
How to create a type from an array of objects in TypeScript?
Given a countries array like this:
const countries = [
{ name: "Australia", code: "AU" },
{ name: "Japan", code: "JP" },
{ name: "Norway", code: ...
1
vote
1answer
23 views
TypeScript: dynamic union type derived from an object value
I want to derive a union type from a table-like input object. I've succeed with a working solution but I suppose there should be shorter / more straightforward way. Here's the input object:
const ...
0
votes
1answer
23 views
Issues with handling union vs intersection Typescript
I'm trying to build out an interface with a couple methods, then calling those methods based on an incoming piece of data being one of the keys of that object.
Here is my type:
type LogicalFunction<...
0
votes
2answers
49 views
TypeScript: Why can't I access a property on a Union Type which is only defined on one object?
I want to have either an object with the property a which is a number or an object with property b which is a string. In plain JavaScript the variable test would be either a number or undefined if the ...
0
votes
1answer
40 views
How to define a union of a type in an external file in Raml datatype fragment?
First, this question is similar to, but different from How to define an array of a type in an external file in Raml?, except I want to make a DataType (A) that has a property that is a union of two ...
1
vote
1answer
38 views
Typesafing Recursion Through Generics?
I'm trying to find a way to typesafe a recursion (which returns a number by the end) using generics.
What I tried:
function recursion<N,T>(value:N, lim:N):T|N {
if(value < lim) return ...
1
vote
2answers
96 views
Pattern matching over nested `Union` types in Python
Building a Python library, I am using type hints to guarantee consistency over certain data representation. In particular, I am making use of Union (sum types) in a nested fashion to represent the ...
0
votes
1answer
19 views
TypeScript How to make String Union Type to a concrete Obnject Type?
how can i implement this:
type ActionNames = 'init' | 'reset';
type UnionToObj<U> = {/* TODO HERE */}
type Result = UnionToObj<ActionNames>;
// expect type Result to be `{ init: any, ...
0
votes
0answers
28 views
Can I create a type guard for a string union type that doesn't require duplicate data?
I have multiple string union types that are combined into an overarching union type:
type optionsAll = optionsA | optionsB | optionsC
type optionsA = 'a' | 'b' | 'c'
type optionsB = 'a' | 'd' // The ...
0
votes
2answers
66 views
Destructure/access a property that may or may not exist on an object union type
I get the following errors:
type Union = { type: "1"; foo: string } | { type: "2"; bar: number };
function doSomething = (object: Union) => {
const { foo } = object
// ...
0
votes
2answers
36 views
TypeScript: Factory function for union types
I have a custom Factory type that lets me create factory functions.
export type Factory<T> = (state?: Partial<T>) => T;
I have an <Avatar /> React component that has a union type ...
1
vote
2answers
80 views
Type Narrowing not working as expected with generic constraints
I have a situation where the generic type is constraint by a union type, but I find that doing this does not make the type narrowing to work as expected. The code snippet below shows what is going on.
...
1
vote
1answer
44 views
Array<Union of type>to Array<Union of generic type>
I'm trying to define the relationship between two array type, related by a Wrapper generic type:
interface WrapperType<T> {
innerValue: T;
}
type InnerArrayType = (TypeA | TypeB | TypeC)[];
...
2
votes
0answers
53 views
Typescript conditional types not able to correctly narrow type for nested properties
I encountered a strange issue. I'm wondering if this is genuine bug or just the lacklusterness of typescript's conditional types.
Consider this interface-
type EnumObj = { enm?: readonly (string | ...
1
vote
2answers
26 views
Restricting an interface to specific keys from a union type
I've got a union type listing some allowed keys :
type AllowedKeys = "a" | "b";
Somewhere else, I'm declaring an interface, and I want to restrict this interface to the allowed ...
0
votes
2answers
59 views
Typescript generic interface with union type
I want to use an interface with generic union types like this:
interface IOperator {
<U>(a: U[], b: U[] | U): boolean
}
export const intersects: IOperator = (a, b) => a.some((el) => b....
0
votes
1answer
24 views
Using a union but getting an error that the prop does not exists
I've got a variable which type is a union:
const waypoint: Waypoint;
The Waypoint type is a union of 2 types:
type Waypoint = UtmNZ | GeoNZ;
export interface GeoNZ {
latitude: number;
longtitude:...
1
vote
2answers
70 views
Does Scala support an OR composition?
That question may be a dumb one where any search engine should give me a quick answer. However I did not find anything, so I may use the wrong terms.
If F# one can do an exclusive (OR) composition ...
1
vote
1answer
179 views
Union type assignment issue with React/Redux/Typescript setup
I do have a pretty specific problem with an application setup utilising React, Redux and Typescript.
I planned on simplifying my reducers by following this article from medium and up to this point (...
0
votes
1answer
42 views
TypeScript DeepMap Union type with if statement
I'm trying to create a Union type with the structure of optional fields. I have created the following types:
export type StartEndType = {
start_date: string;
end_date: string;
};
export type ...
0
votes
0answers
29 views
TypeScript Define Single Type for Union Types
In my TypeScript I have many methods like this and in any method witch have the same parameter or return type I should repeat these union types:
foo(bar: 'a' | 'b' | 'z' | 'AA'){
}
Is there any way ...
0
votes
1answer
53 views
F# Reflection Expr.NewUnionCase with FSharpType.GetUnionCases and/or Type.MakeGenericType
let recordType = ... // omitted
let resultTypeRaw = typedefof<Result<_,_>>
let resultType = resultTypeRaw.MakeGenericType([|recordType.AsType();typeof<string list>|])
Expr....
0
votes
1answer
34 views
In Typescript, how to understand 'extends' of union types?
Here is my try:
type Comb1 = "123" | "1234";
type Comb2 = "123" | "1234" | "12345";
type Res<T, U> = T extends U ? T : never;
// Res1 === &...
1
vote
0answers
33 views
Use of ''instance of' in union types. ts(2358). Left side of instance of must be 'any', object or a type parameter
Following this question, have this code: (See line with comment //ERROR: ts(2358))
const w = ((mat: Float32Array | Vec4) => {
if (mat instanceof Float32Array) {
const sizeIsOk = mat....
2
votes
2answers
37 views
Refining union type
This does not compile:
type FormatTypes = {
text: string,
binary: Array<number>
};
type Format = keyof FormatTypes;
type FormatType<F extends Format> = FormatTypes[F];
type ...
1
vote
2answers
30 views
TypeScript add properties to specific union cases
I have this type (simplified):
type T1 = {
kind: 'a';
prop: string;
} | {
kind: 'b';
prop2: number;
};
Now I want to add a property prop3: boolean but only to the case of kind: 'a', like I ...
0
votes
1answer
21 views
Pacts: How to match a sum / union type?
I have an api endpoint which shall return an array of a sum type. How can I write an appropriate matcher for it in pacts (javascript version, consumer site)?
Example: Imagine we have the endpoint /api/...
2
votes
1answer
43 views
A way to distribute string union to another Type
I currently have some Typescript code that looks like this :
type UserRole = "admin" | "partner" | "associate";
type User<Role extends UserRole> = {
// ...
...
0
votes
0answers
45 views
TypeScript protected property not visible in union
I have the following TypeScript snippet:
class A {
protected x: any;
}
class B {
protected x: any;
}
const fn1 = function(this: A) {
return this.x; // works
};
const fn2 = function(this: A|B) ...
1
vote
0answers
25 views
Type of an array containing typed objects and/or paired elements of known types
I have an array that holds a repeating pattern of values, where each repetition consists of one or two array elements of known types.
See the type Sequence below, which works for bounded numbers of ...
2
votes
0answers
25 views
TypeScript do not require all index properties [closed]
I have the following code:
type AZ = 'a'|'b'|'c'|'d'| ... |'z'; // union of many types
type Mapping = {
[K in AZ]: string;
}
const obj: Mapping = { // error, missing properties 'c', 'd', etc.
a: ...
0
votes
2answers
167 views
Custom TypeScript type of literal strings using union type does not equal string
I tried researching online, but I didn't find any solution to my problem. However, I've been awake for some time so that might be the reason that I didn't find it.
I have the following custom type
...