Questions tagged [type-safety]

Type safety is the extent to which a language discourages using variables in an unsafe manner, according to the variables' type.

Filter by
Sorted by
Tagged with
1 vote
1 answer
111 views

Type safety doesn't work with Angular dependency injection

I lose typing when I use Angular's dependency injection. I don't know why? Can someone explain and find a solution to use DI while having strict typing? I'm using a service to strictly type local ...
Tim's user avatar
  • 172
0 votes
0 answers
15 views

Seeking Recommendations for Lightweight Libraries for Strongly Typed TypeScript RESTful API Endpoints

I am currently exploring lightweight options for constructing strongly typed TypeScript RESTful API endpoints in a Node API service and am interested to know what libraries or tools the community ...
user1525248's user avatar
0 votes
0 answers
20 views

How do I enforce a maximum depth and value requirements for a multi-dimensional object containing objects and arrays of primitive (only) values?

Introduction: I have a multi-dimension object in a TypeScript file, that would look something like this: const store = { key_1: "value", key_2: 123, key_3: true, key_4: { key_4_1:...
Malekai's user avatar
  • 4,783
0 votes
0 answers
24 views

TypeScript returning arbitrary type

I have a function that, when called, returns an object. The type of the object is unknown to the function, but supposedly known to the caller. I don't want to use any or implicit any, so I have to ...
noamtm's user avatar
  • 12.5k
-1 votes
1 answer
72 views

Is it possible to create a Builder like this in C#?

var pipeline = new PipelineBuilder<string> .AddInitial(n => n*12) .AddStep(n => n.ToString()) .Build(); Executing `pipeline(2)' should return "24". Also, the type ...
SuperJMN's user avatar
  • 13.2k
0 votes
0 answers
38 views

D-Bus: type-safe usage of signed 8-bit integers

According to the D-Bus specification, there are signed and unsigned types for 16-, 32- and 64-bit integers. However, for 8-bit integers, only an unsigned type ('y') is defined. Background: I am ...
S. Gleissner's user avatar
4 votes
2 answers
74 views

Differences between type-safety and value-safety

I've been reading Head First Object-Oriented Analysis and Design book and I'm trying to learn oop. in one of the pages of this book, I've read these lines: we’ve made the application less fragile ...
Mehdi's user avatar
  • 93
0 votes
2 answers
98 views

Out of bounds check in C with clang-tidy

Why I can easily detect this trivial case of out of bounds array accessing (marked as OK), using clang-tidy, but I can't detect the one marked as KO? I understand pointer decay in C, but I would ...
Sam's user avatar
  • 27
-2 votes
2 answers
55 views

How can you have a template function in C# which match only a special subset of good types with no common interface?

I would like to be able to write some C# code the non-repetetive way, using generics, like this: var t = someObject.CallMethod<T>(); or someObject.CallMethod(t); where caller supplies ...
Tim Lovell-Smith's user avatar
0 votes
0 answers
57 views

JSDoc Types for Runtime Validation

We are currently considering adding JSDoc with typing / type safety to our projects. We favor JSDoc with types over Typescript because we write mostly self-contained functions and don't want the ...
Misun's user avatar
  • 21
2 votes
1 answer
87 views

Difficulty in trying to implement a type-safe `at` for length-indexed vectors

I have just learnt about the DataKinds extension, type-level literals, and found out that type-levels natural numbers can be compared using constraints provided in the Data.Type.Ord such as (>), ...
Futarimiti's user avatar
4 votes
1 answer
98 views

How to do type-safe indices in Swift?

I'm trying to do something like this: typealias HumanId = Int typealias RobotId = Int func getHuman(at index: HumanId) -> Human func getRobot(at index: RobotId) -> Robot but as it is now I ...
Paulius Liekis's user avatar
-1 votes
1 answer
46 views

how 1 +"2" works in C#

I was reading about the type safety in C# like how we can't assign an integer value to a bool etc., which made me to do some experiment. I executed a code snippet hoping that it will give a compile ...
Aman singh Parihar's user avatar
0 votes
1 answer
47 views

Only permits children classes as generic parameters

Java 17 I'm implementing the following method: public static <T, O extends T, V> Optional<V> toOption(T t, Function<? super O, ? extends Optional<V>> f, Class<O> cls){ ...
Some Name's user avatar
  • 8,576
0 votes
0 answers
61 views

How to make generic type deque?

I am creating a deque using generic type E... Having trouble initializing some sort of generic array, while being type safe, have tried casting, however this is Type safety: Unchecked cast from Object[...
luh_marc808's user avatar
2 votes
2 answers
61 views

How to perform safe pattern matching on existential types in Scala 2.13?

Note: This is a contrived example. Consider the following existential type. sealed trait Showable final case class Show[A](show: A => String, value: A) extends Showable I can define a show method ...
Aadit M Shah's user avatar
2 votes
2 answers
216 views

Angular type of Components

I have a routesList that I use in the app-routing.module of Angular The type of the routesList is: type routesList = { [key: string]: { path: string; title: string; component: Type<...
ross's user avatar
  • 23
-1 votes
1 answer
159 views

logic gates in xml file and python (fault tree analysis )

I want to make fault tree analysis of system using python and xml file, but I couldn't find enough material to help me in that. Let say I have a simple xml file which has Top event and OR logic gate ...
Daly's user avatar
  • 1
2 votes
1 answer
477 views

Alternative for "any function" ((...args: any[]) => any) without using any

I wonder if there is an alternative way to specify the function type "any function" that does not use any (and therefore improves type-safety). To clarify, I am searching for an alternative ...
Islingre's user avatar
  • 2,040
0 votes
1 answer
69 views

Convert key-value map to type with required fields (or fail) in Typescript

I have two types of interest, and a collection: type One = { 'type': 'One'; a: string; x?: string; } type Two = { 'type': 'Two'; b: string; y?: string; } const collection: ...
qqq's user avatar
  • 1,390
0 votes
1 answer
55 views

Kotlin - reflection and type safety

I am writing a small library for programatically generating SQL queries. The goal is that the API of this library can be used like that: myQuery.where( MyClass::id equal "foo", ...
Alkis Mavridis's user avatar
5 votes
3 answers
1k views

How to type-safely remove a property from a TypeScript type

Let's have the following two interfaces: interface A { foo: string; bar: number; } interface B { foo: string; } How can I type-safely convert an object that conforms to A to one that conforms ...
Jonas Sourlier's user avatar
0 votes
0 answers
137 views

What is the most runtime-performant and safest enum-like type I can define in C++?

Assume all I need is a type Color inhabited by only 3 values, red, green, blue, (just like bool is inhabited just by 2 values, true and false), and the ability to tell those 3 values apart from each ...
Enlico's user avatar
  • 23.6k
0 votes
2 answers
118 views

About the value of a scoped enum containing a value of the underlying type that does not correspond to any of the enumerators

Basically, given enum class Color : int { R, G, B }; Color c; is there any way for c to end up holding something other than R, G, B? Or, in other words, an underlying int other than 0, 1, or 2? I ...
Enlico's user avatar
  • 23.6k
6 votes
1 answer
110 views

Typescript: Ensure all properties use the same tuple type

I've got a function with a generic that is a tuple of 1 or a tuple of 2 elements. I want to ensure that all properties used in the function use the same length tuple. type TypeA = [string] // Tuple of ...
Hendrik Jan's user avatar
  • 4,476
2 votes
0 answers
46 views

Can I create a lookup object of functions in TS that share an object param with different type unions?

Let's say I have these functions that share the same signature: type ProcessFunction<U> = (options: { type: U }) => void; const createStuff: ProcessFunction<"monkey" | "dog&...
Julio García's user avatar
0 votes
1 answer
60 views

Write transformation in typesafe way

How do I write the below code in typesafe manner in spark scala with Dataset Api: val schema: StructType = Encoders.product[CaseClass].schema //read json from a file val readAsDataSet :CaseClass=...
Dot Net Dev 19's user avatar
0 votes
1 answer
89 views

SQL placeholder using character versus numeric values

I am trying to get more familiar with placeholders to to run SQL commands from python, but cannot successfully pass character commands. Here I describe a simplified solution that will be scaled up. In ...
Nick Crouch's user avatar
0 votes
2 answers
47 views

Is is possible to force passing the key of a resource file entry, not the value?

I want to be able to retrieve a language dependent string during runtime, why I created the class below. It let's me get the value in the preferred language whenever I want with getValue(): internal ...
tickietackie's user avatar
0 votes
1 answer
54 views

Automatically use subclass type in method signature

I have a parent class with many subclasses in Python 3. Currently, the hierarchy looks something like this: class Parent: @classmethod def check(cls, obj: "Parent"): pass ...
Mew's user avatar
  • 376
5 votes
0 answers
98 views

How can I make two identical types two distinguishable types [duplicate]

How can I make non-primitive types A and B two distinguishable types in order to add type safety to the interface of function f? constexpr std::size_t type_size{ 8U }; using A = std::array<char, ...
user2672165's user avatar
  • 2,986
2 votes
0 answers
191 views

How to create a fully type-safe NestJS package with dynamic objects in TypeScript?

I am currently working on a personal project to provide easy access to different storage providers through a NestJS package. I want the package to be fully type-safe but I am experiencing difficulty ...
samsepi's user avatar
  • 41
0 votes
1 answer
57 views

How to infer parameter type of a overloaded callback?

I'm trying to define a type-safe nodejs-style callback in typescript. I would like to have err defined as Error if present or data as T if not. If I use this code export interface SafeCallback<T&...
Diego Ferri's user avatar
  • 2,667
0 votes
1 answer
76 views

Is there a way to force indexing to require an enum class for type safety?

Let's say I have an array of integers, one for each member of a particular enum class. I can cast the enum class to an int to index the array but I'd rather use the enum class for type safety since ...
GLJeff's user avatar
  • 139
1 vote
1 answer
53 views

How to have type-safety dependent on a number? (like generics are dependent on a Type)

I want a Type that is "for" a certain number, and another Type for another number. But I don't want to have to manually define a Type for each number like Level1024 and Level1000. I want it ...
ispiro's user avatar
  • 26.6k
1 vote
3 answers
128 views

How to make `enable_if` a hard requirement

This answer contains the following code: #include <type_traits> template< typename T, //real type typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::...
ByteEater's user avatar
  • 897
0 votes
0 answers
16 views

Make TypeScript null comparisons throw error [duplicate]

In TypeScript, if you try to compare a string to a number you get an error, because the string would never be a number. Why doesn't TypeScript through an error if you compare the same string to null? ...
kim3er's user avatar
  • 6,326
2 votes
1 answer
405 views

Does allowing extra parameters break type safety in TypeScript?

Consider this example: (playground) type F0 = (x?: string) => void type F1 = () => void type F2 = (x: number) => void const f0: F0 = (x) => console.log(x, typeof(x)) const f1: F1 = f0 ...
Victor's user avatar
  • 753
1 vote
1 answer
60 views

OCaml 5.0.0~beta1: How to use an argument of Effect when their effect handler is not specified (Using Unhandled Exception)

I am using opam switch: 5.0.0~beta1 I was playing around with some simple functions (on utop): type _ Effect.t += Foo : (unit -> unit) -> unit Effect.t let a = try perform (Foo (fun () -> ...
Eclipse 's user avatar
0 votes
1 answer
855 views

Pass readonly parameter to mutable function (which will not mutate)

I need to create a function batchUsers which takes a readonly string as a parameter to create a DataLoader. In my batchUsers function I need to call a function (User.findby) which has defined its ...
sev's user avatar
  • 1,550
0 votes
0 answers
142 views

Angular 14: Is creating an object directly in the template resource heavy

I am trying to implement transloco (an internalization module), normally i was using typescript arrays and objects to pass data to children. But to do that while using transloco, I need to subscribe ...
ertucode's user avatar
  • 560
-1 votes
1 answer
342 views

property map does not exist on type string | Array<string>

This is how I have defined defined default value in interface , because sometimes it is string and othertimes it is array, I am doing map, when I am sure it will be array. however I get the ts error ...
Akshay Vijay Jain's user avatar
0 votes
1 answer
40 views

TypeScript infer type by its unique field

I have a composite type called IncomingMessage export type IncomingMessage = | MessageText | MessageGameStarted //| ... rest export type IncomingMessageType = | IncomingMessage['messageType'] ...
4nnihil4tor's user avatar
2 votes
1 answer
141 views

Type-safety for Patternmatching on Parameters with Dependent Types in Scala

I am currently working with a type hierarchy which represents a tree and an accompanying type hierarchy that represents steps of root-to-node paths in that tree. There are different kinds of nodes so ...
Gondlar's user avatar
  • 53
1 vote
1 answer
113 views

Wrapping a generic type into an object allows for unsafe assignments

I’m confused by the code below. I have a type such that Type<boolean> is not assignable to Type<true>, but if I wrap it into an object type (BoxType below), then suddenly BoxType<...
Guillaume Brunerie's user avatar
0 votes
0 answers
27 views

(c#) How can Initialize a generic type with it's type argument object through it's non-generic base class with type safety

I have an ability data factory which has a generic function for creating specific types of abilities. The abilities themselves need to have their own unique AbilityData object passed in which contains ...
Sebastian King's user avatar
3 votes
0 answers
481 views

TypeScript + React | How to type check all Component props

How can I make sure that TS is type checking all available properties of a component? The moment one property is incorrect, the rest of the "upcoming" props are not checked anymore - at ...
Nico W.'s user avatar
  • 103
1 vote
1 answer
1k views

Check if an object has a property of a certain type

I'm trying to work out how to use generics to convert a date which is split into multiple parts into a Date object. So far, I have this: export const convertDate = <T, K extends keyof T>(obj: T, ...
Pezholio's user avatar
  • 2,459
2 votes
1 answer
667 views

How to build a type-safe multiple property groupBy in typescript

I already had a groupBy function which receives an array of objects and a key. It is capable to group by a single property. const groupBy = <T extends Record<string, unknown>, U extends keyof ...
Omar Omeiri's user avatar
  • 1,546
2 votes
1 answer
51 views

Property does not exist on union interface type

I have an object that contains an array of team members, the smallest object-type implements either interface Member or interface Manager. Manager-objects can contain other interface Member objects. ...
John Wick's user avatar

1
2 3 4 5
14