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.
649
questions
1
vote
1
answer
17
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<...
0
votes
0
answers
19
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 ...
1
vote
0
answers
64
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 ...
1
vote
1
answer
50
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, ...
2
votes
1
answer
37
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 ...
2
votes
1
answer
29
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. ...
0
votes
0
answers
40
views
Getting or generating Typescript types for REST api
I am consuming webhooks from and making REST requests to a server. How can I get the typescript types for the data I get from the server? With graphql there are some libraries which can automatically ...
1
vote
1
answer
54
views
Typescript property does not exist on type when using a type where property should exist
I am using a function which takes a message handler function as an argument. The message handler is defined as:
export declare type MessageHandler = <EventType extends AnyEventName = AnyEventName&...
0
votes
2
answers
23
views
How can I correctly type this object converting?
How can I achieve typesafety for this converting case? I'm mapping over the palette and convert any object with entries to key value pairs, like tailwindcss does for their color configuration. However ...
0
votes
1
answer
38
views
Using FirestoreErrors in Cloud Functions
How can I use the FirestoreError class in my Firebase cloud functions?
I want to throw errors of type FirestoreError when the document or field I am looking for is undefined in Firestore:
throw new ...
0
votes
1
answer
137
views
TypeScript types to restrict array values
Can I use TypeScript types to restrict array inputs to certain elements?
For example, if I wanted to create a type that is an array that could hold any number of elements, but the elements are ...
0
votes
3
answers
102
views
Why Int and Float literals are allowed to be added, but Int and Float variables are not allowed to do the same in Swift?
I tried adding an Int and Float literal in Swift and it compiled without any error :
var sum = 4 + 5.0 // sum is assigned with value 9.0 and type Double
But, when I tried to do the same with Int and ...
0
votes
0
answers
51
views
JSON serialization with strong type checks enabled in the Dart Linter
I decided to turn on stricter type checks and turn on a lot more Linter rules in Dart. Currently, I am wondering what the best practice is regarding serializing JSON and strong type checks.
I receive ...
0
votes
0
answers
7
views
pairing classes of certain types
I have an architecture where I have two base classes A and B that does not reference each other directly. I have a class, C, which takes an instance of A and an instance of B. Now what I want to do is ...
1
vote
0
answers
47
views
Why is a function with a required parameter assignable to a function type where the parameter is optional
Question
Simply put, I wonder why the following is valid:
type Func = (param?: string) => void;
const func: Func = (param: string) => {
return;
};
The problem
In practice, this becomes a ...
0
votes
1
answer
47
views
Hibernate: EmbeddedId with auto increment
Suppose that I have a simple Hibernate entity with auto-incremented id.
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = IDENTITY)
private ...
1
vote
0
answers
14
views
Usage of NamedType and type_safe implementations
Recently, there was a talk in my team to use strong types. After a bit of reading different blogs, I am inclined towards avoiding Primitive Obsession and have found below 2 implementations.
NamedType ...
0
votes
2
answers
34
views
Type safety in Dart using Container
I found something strange in dart. If there is a list that contains instances of a base class (in this example Super), the list can be set with a list of inherited instances. It seems that this ...
0
votes
0
answers
17
views
TypeScript: number|undefined variable produces string output [duplicate]
In our application we recently faced a hard to find bug, and it turned out that one of our TypeScript number|undefined variable strangely produced a string output.
I managed to narrow down the a ...
1
vote
1
answer
80
views
How to check for exhaustiveness of product types in TypeScript?
It's very easy to check for exhaustiveness of sum types in TypeScript.
type Sum =
| { tag: 'num'; value: number }
| { tag: 'str'; value: string };
const len = (sum: Sum): number => {
...
0
votes
0
answers
37
views
Is it good practise to declare all html elements with an ID as a variable automatically in a for loop at the start of your code? [duplicate]
I wrote this code which loops through all elements with an ID, and declares a variable with the same name as the ID refering to that element. The code works as expected and by using this at the top of ...
1
vote
1
answer
74
views
Can rust reason about lifetimes on all control flow paths? [duplicate]
Consider the following example:
impl Foo {
fn measure<'a>(&'a self) -> Vec<&'a Bar> {...}
fn try_action<'a>(&'a mut self) -> Result<(), Vec<&'a ...
3
votes
2
answers
112
views
Typescript narrow parameter type based on discriminator
I have a legacy API as shown below (playground link)...
type Command1 = {
cmd: "my first command",
arg1: string,
arg2: boolean
}
type Command2 = {
cmd: "my second ...
1
vote
1
answer
34
views
Encapsulating Parameters and Arguments in classes
I have sort of an open question, but I have tried quite a few solution and none of them are really satisfactory I would say so hopefully someone here has an idea of whether I am missing some solution.
...
0
votes
2
answers
70
views
Compatibility of argument types
I wonder if my thinking is correct, or I'm making some big mistake. Let's have simple code:
class A { String a = "a"; }
class B extends A { String b = "b"; }
void goofy(Map<...
0
votes
3
answers
131
views
Creating a constexpr enum-like type
I've been using enum class FooEnabled : bool { no, yes }; as a way to create type-safe bools. It works well, except I'd like to add explicit conversion to bool, Boolean operators like operator!, etc. ...
3
votes
0
answers
222
views
Argument of type '{ [x: string]: string; }' is not assignable to parameter of type
I created a custom React hook "useForm" in TypeScript. I wanted to be more type-specific so in getTextChangeHandler, I require the parameter to be a key within the state, as follows:
useForm....
2
votes
1
answer
45
views
ocaml, ability to trigger compile error on value change
I'd like to express, in a compile time way, that my code operates under the assumption of a value being a certain constant. For simplicity, let's say I have this module
module Lib : sig
type t = A|B|...
2
votes
1
answer
165
views
Does Typescript allow mutations that break type safety?
In the following snippet, is it demonstrated that Typescript cannot warn against mutation of strictly typed objects in a way that violates the constraints of its type?
type Animal = {
name: 'cat'
...
1
vote
2
answers
449
views
TypeScript type-safety fails with JSON.parse
Am I wrong or does type-safety get thrown out in TypeScript when parsing JSON?
I should be getting an error here, but I don't:
interface Person {
name: string
}
const person: Person = ...
0
votes
1
answer
57
views
Prevent improper use of a User Defined Data Structure and Making DS resuable
Objective:
Define a Priority Queue Implemented with a Max Heap
Provide as much type safety as possible and provide an implementation that is flexible/reusable (even though python is dynamic and only ...
1
vote
1
answer
163
views
Scala 3 collection partitioning with subtypes
In Scala 3, let's say I have a List[Try[String]]. Can I split it up into success and failures, such that each list has the appropriate subtype?
If I do the following:
import scala.util.{Try, Success, ...
1
vote
1
answer
203
views
Why simple interface can't assign to Record<string, any>?
Trying to create generic type for CSV file.
export interface Row {
id: number;
name: string;
}
export type CsvFile<T = Record<string, any>> = {
data: T[];
headers: Array&...
0
votes
0
answers
20
views
Type safe spreadsheet file importer
I'm trying to import an (for example) Excel file and use its' values later while keeping the whole thing type safe, for this I've got following code to declare the expected columns and their types:
...
0
votes
0
answers
45
views
Type safety when (de)serializing with a custom converter annotation
So if I have a custom type with a custom deserializer in Newtonsoft.Json:
[JsonConverter(typeof(SomeTypeJsonConverter), MyCustomSomeTypeConverterParameter)]
SomeType MyProperty { get; private set; }
...
-2
votes
2
answers
86
views
Is there a way to declare a 2 dimensional array of List in a type safe manner in Java? [duplicate]
Here is the code I have that works but with a type safety warning when I size and instantiate the array:
import java.util.ArrayList;
import java.util.List;
public class Test {
private static ...
1
vote
1
answer
60
views
how to use Typescript values in subobject?
I am still very new to programming and typescript.
I hope I can explain my question reasonably well, unfortunately I could not find a solution online.
I have a value variable like this for emails:
...
0
votes
1
answer
57
views
How do I require that an enum has certain members
I'm designing a lib API which involves some finite state-machines, so let's say that the lib exports the following interface:
export interface FSM<TStates> {
state: TStates
// ... other ...
0
votes
0
answers
50
views
Is there a way to add memoization for existential types?
I'm searching for an advice how to cache some data which comes from source with existential type. Let me show you an example of what I mean. This is synthetic example, just to highlight the problem.
...
1
vote
1
answer
64
views
In C#, how can I add instances of FluentValidation using reflection?
Currently, I’m adding validators in the Startup.cs like:
public void ConfigureContainer(ContainerBuilder builder)
{
Register<Signer, SignerValidator>(builder);
...
2
votes
2
answers
483
views
How do I create a map from a class in order to extract its properties as values?
I would like to create a stronger type-safe link between an Angular template and a FormGroup. I thought of the following but I do not know how to express it in TypeScript properly.
I want to use an ...
0
votes
1
answer
217
views
How does Kotlin achieve type-safety by eliminating checked exceptions?
I am a newbie to Kotlin programming. While going through the advantages of Kotlin over Java I came across this claim that by avoiding checked exceptions Kotlin achieves type safety. Also I do not ...
0
votes
1
answer
62
views
Is there a way to configure which unsafe Groovy operations to allow?
Groovy allows various non-type safe operations that would be allowed in Java at compile time (and sometime runtime).
For example, assigning a list to an array is allowed:
Integer[] a = [1, 3]
So is ...
0
votes
1
answer
88
views
Python: Referencing a class attribute
I want an atrribute in my class to reference an a attribute in a different class.
This isn't good enough because it refereces only the class, not the member:
class Foo
x: Bar
If it was C++, I would ...
1
vote
1
answer
135
views
How to use a proper type Function on a generic function?
I'm trying to fix the @typescript-eslint/ban-types lint errors:
warning Don't use Function as a type @typescript-eslint/ban-types
I agree that Function is an unsafe type and should be replaced ...
4
votes
1
answer
88
views
Using generics and Class of an object in map
I have following class/interface structure (can't modify the source):
public interface Car {}
public class CarA implements Car{
public String getASpecifics() {...}
}
public class CarB implements ...
-2
votes
1
answer
132
views
A class with toString() can be used as a string, but how to convince the TypeScript compiler?
My class implements toString() to allow me to use any instance conviently as a property name when building up other objects. The TypeScript compiler though is not convinced and outputs: a computed ...
2
votes
2
answers
55
views
Why doesn't the following TypeScript program throw a type error?
Consider the following program.
interface Eq<A> {
eq(this: A, that: A): boolean;
};
class Pair<A> implements Eq<Pair<A>> {
constructor(public x: A, public y: A) {}
eq(...
0
votes
2
answers
103
views
Flow - typesafe actions
I'm using flow and I want to make my reducers more type safe. I came across this comment that suggests a solution that I find kind of nice and fitting inside my codebase:
https://github.com/reduxjs/...
1
vote
2
answers
2k
views
How to write typescript typeguard method for function type
export const isFunction = (obj: unknown): obj is Function => obj instanceof Function;
export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[...