161
questions
1
vote
0
answers
53
views
In python, how do you assert the type of a variable after checking it? [duplicate]
Overview
There is a general pattern in programming that goes like this
if (something is not initialized) {
initialize the thing
}
do something with the initialized thing
In python, I have an ...
1
vote
1
answer
64
views
How does typescript check valid when type assertions happend in typescript [duplicate]
I am learning type assertion concept in typescript. After Reading tutorial offical documentation, older version and some others, I have been confused about how typescript evaluates type assertions as ...
0
votes
0
answers
20
views
Why does NSwag's Typescript Client assert `null as any`?
Template code: https://github.com/RicoSuter/NSwag/blob/master/src/NSwag.CodeGeneration.TypeScript/Templates/Client.ProcessResponse.Return.liquid
Generated code looks something like:
protected ...
0
votes
0
answers
14
views
User-defined type assertion guard for builder results in data field being null
I am trying to make a builder that allows for both chaining and type assertions.
Chaining is working fine.
Assertions, however, are not updating the data correctly.
type BuilderSchema = {
[k in ...
2
votes
1
answer
116
views
Is it possible to avoid the type assertion in this generic function body?
As a use case, I want to allow people to add an arbitrary function to an object, and call that function through another, using its name and parameters.
// Example arbitrary function
const sum = (a: ...
-1
votes
1
answer
77
views
How to assert that a string can be used as an array index w/o converting/asserting it to/as a number?
I have a string value, which I intend to use as an index of an array. I'm sure of this value and want to assert that it's a valid 'index value', w/o converting it to a number at runtime or asserting ...
2
votes
1
answer
54
views
Enforce at compile time that a type is NOT narrowed
Inspired by this article I am using a pattern now that returns errors instead of throwing them (like in golang or fp-ts). I extended the code in the article with some more typing. This way it is ...
0
votes
0
answers
39
views
Expected TypeScript to Enforce True "Node" Instance Assignment, but Getting Property Missing Error Instead
Original Question:
I'm trying to type a variable in TypeScript such that it should only hold an actual instance of a Node (or a derived type, e.g., TextNode, HTMLElement, etc.) and not just any object ...
1
vote
0
answers
114
views
Union types do not work when combined with `Omit<>` [duplicate]
I have the following interfaces:
export interface Base {
a: string;
b: string;
}
export interface Foo extends Base {
c: string[];
type: 'foo';
}
export interface Bar extends Base {
c: ...
1
vote
1
answer
145
views
TS reuse this.constructor in parent method
I have a base Message class and an subclass SpecializedMessaged for extra features
class Message {
constructor(
readonly content: string
) { }
edit(replacement: string) {
...
1
vote
1
answer
121
views
Why does TS Lose Type Inferences When Spreading
Update 1️⃣
As per comments, I did create a standalone example of what seems to be the same situation:
interface Person {
name: string;
age: number;
}
type People = Person[];
const p: Person = {
...
0
votes
0
answers
23
views
Why do assertion methods work on private class members only when intersecting with public members?
I am working with typescript. In my code, I am doing a type check via an assertion method for a private member. After research, It appears that you cannot type guard private class members. For example,...
1
vote
1
answer
520
views
What's the correct way of returning one of different result values in one func in Golang?
I'm new to Go and was hoping to get some insights from more expirienced devs.
In my main function I call a 'Prepare' function that takes an enum as an argument. The enum is one of three options: A, B, ...
2
votes
1
answer
392
views
Validating whether return value satisfies Conditional Type in function signature
I'm trying my hand at porting Scott Wlaschin's "Railway Oriented Programming" concept to Typescript.
I'm trying to get the types correct for the either function. I think my code below ...
0
votes
1
answer
52
views
How type assertions "as" work in typescript
Explain how as works please:
I have a simple interface.
interface myModel {
name: string;
id: number;
}
and there is a function that returns an object { } as myModel;
function getMyModel(): ...
0
votes
1
answer
141
views
typescript setState from Context is possibly undefined
Typescript complains that my setReposlist is undefined. I am confused because I think have previously typed using this interface:
export interface ReposContextInterface {
reposList: {},
...
1
vote
1
answer
488
views
Async error in typescript react component
I have this react component, that I wish to get a payload from api so that the component can use later.
const AccordionCard = async ({username}:AccordionCardProps) =>{
const repos = await axios....
0
votes
1
answer
479
views
Type is not assignable when using array map to pass in react component
I want to iterate a react component based on array data I have in payload.
interface PayloadItemInterface {
login: string
}
const QueriesAccordion=()=>{
const SearchPage = useContext(...
0
votes
1
answer
39
views
Property does not exist on type "Interface | undefined"
I have this context
export type SearchBooleanContextInterface = {
isSearched: IsSearched,
setIsSearched?: Dispatch<SetStateAction<IsSearched>>
}
export interface ...
0
votes
1
answer
91
views
passing variable on react handler typescript
I wanted to pass a variable (SearchBoolean) to be logged everytime a button handler function is invoked. So I did this:
type SearchFormProps = {
styles: React.CSSProperties;
classNames: string;...
0
votes
1
answer
309
views
Move type assertion within function that returns any
I have the following example of generic Go function:
package main
func read(address uint16) any {
switch address {
case 1:
return float64(0.5)
case 2:
return int(8)
...
-1
votes
1
answer
59
views
TS: Array to object type conversion
I have the following value:
const MY_CONST = [
{
id: 1,
name: "ITEM_1"
},
{
id: 2,
name: "ITEM_2"
}
] as const;
I would like to reduce the value to a typed ...
-1
votes
1
answer
138
views
How to unmarshal json in Go lang, when that json could be one-of-many different types [duplicate]
I am pulling some data out of a database with Go, and one of the fields of that structure is a JSON field that can be one of several types. How can I cast the parsed json to the correct type in Go?
...
2
votes
1
answer
496
views
How to compare generic number type
I have a validation function Positive, it's works but looks ugly.
type Positiver interface {
decimal.Decimal | int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | ...
2
votes
0
answers
29
views
Why can't TypeScript automatically assert types in this example? [duplicate]
interface Model {
a: string | null;
}
interface ModelA {
a: string;
}
function myFunc(m: ModelA) {
console.log(m.a.length);
}
function ModelFactory(): Model {
return { a: null };
}
const ...
1
vote
1
answer
111
views
Is there a way to use assertion functions with complex validations without creating a specific type?
I'm receiving data from api and I'd like to add some validations on front-end and get correct types after that validations, but really specific ones.
For example, suppose I'm getting data with type { ...
-4
votes
1
answer
114
views
Go: Type Assertions - Is there an error in the spec? [closed]
Is there an error in the Go Spec Type Assertions?
A type assertion used in an assignment statement or initialization of the special form
v, ok = x.(T)
v, ok := x.(T)
var v, ok = x.(T)
var v, ok ...
1
vote
1
answer
153
views
Why can't TypeScript infer presence of required property in a union term when another prop is asserted to actually collapse the union to one term?
The scenario is that given a function that accepts a single parameter, an object that has type the union between two overlapping types, where one of the union sides has some additional required ...
0
votes
1
answer
382
views
Why does Typescript type assertion not work as expected?
Coming from C# something like this would result in compilation error:
interface IFoo {
a: string
b: string
}
interface IFoo2 {
c: string
d: string
e: string
}
type FooCommon = ...
2
votes
1
answer
550
views
Type assertions and optional chaining in Typescript
I have the following function that performs a simple type assertion, checking that a variable is not undefined or null.
const isDefinedAndNotNull = <T>(val: T | null | undefined): val is ...
-2
votes
1
answer
86
views
Go lang type assertion
I am trying to do dependency injection in golang with applying dependency inversion principle, so I have the following service
package account
import (
types "zaClouds/modules/account/domain/...
1
vote
2
answers
2k
views
TypeScript type assertion generates a message: The character ">" is not valid inside a JSX element
In this code:
export const createCategoriesParams = (filters: string[]) => {
const tags = [...filters].filter(i => i !== 'All');
// eslint-disable-next-line @typescript-eslint/consistent-...
0
votes
1
answer
342
views
How to check if a paramter is an instance of `std::vector`? [C++]
I have a function that takes in a parameter with generic type T. And it will do different things depending on the type of obj.
template <typename T>
void function(const T& obj)
{
if ...
0
votes
1
answer
602
views
Array element type assertion problem in TypeScript
type Plan<T> = [T[], ...T[]];
I declared a type named Plan, which includes a repetitive plan in index 0 and in the rest what to execute initially.
example) const life: Plan<string> = [ [&...
6
votes
0
answers
2k
views
Mocking a File object in NestJs unit test with Jest
I recently started working with Nest.js and its built-in unit testing library Jest, while on a task to upload a .CSV file and perform some operations on it, I decided to also unit test the endpoint ...
-2
votes
1
answer
670
views
Assertion failed for interface as gin.HandlerFunc [duplicate]
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func Foo(ctx *gin.Context) {}
func main() {
var v interface{}
v = Foo
_, ok := v.(func(*gin.Context)...
2
votes
1
answer
1k
views
Get value of interface{ } without having access to type
How can I get the value of x as []interface{} ?
func main() {
var x interface{} = SomeFunc()
fmt.Println(x) // this prints [1 2].
val := x.([]interface{}) // this will not work ...
1
vote
1
answer
544
views
Type '{ [x: number]: any; }' is missing the following properties from Pick<T, keyof T>
I have this code
interface FormState {
cardNumber: string,
month: string,
year: string
}
handleInputChange = (event: React.ChangeEvent<MaskedInput>) => {
this....
0
votes
1
answer
75
views
How to specify type of literal object and comply with TSLint?
TSLint marks both of these as errors:
const a = {} as MyClass; // no-object-literal-type-assertion
const a = <MyClass>{}; // no-angle-bracket-type-assertion
And advices to use explicit typing:
...
2
votes
0
answers
188
views
Why am I fighting the TypeScript compiler with so many type assertions?
I'm new to TypeScript, and I find that I have to frequently add type assertions to compensate for the compiler's chronic inability to narrow types. This makes me wonder if the TypeScript compiler has ...
0
votes
0
answers
213
views
TypeScript user-defined type guard doesn't discriminate for union with optional property
I have two types very similar except for an optional property
type Interval = { start: Date; end: Date; }
type IntervalOpenEnded = { start: Date; end?: Date; }
I want to be able to discriminate them ...
-1
votes
2
answers
10k
views
panic: interface conversion: interface {} is string, not float64
I am trying to convert this simple python function to golang, but facing issues with this error
panic: interface conversion: interface {} is string, not float64
python
def binance(crypto: str, ...
0
votes
1
answer
496
views
Cypress asynchronous execution returns 4 same assertion
I have a question.
I am using Cypress for my automation and I started using async and await for my tests.
I am using POM design pattern.
My question:
If I execute the following test:
test.spec.ts ...
-1
votes
1
answer
890
views
Golang Interface{} wont type assert to int [duplicate]
I’m working on a rest api but for some reason can't type assert an interface{} to its underlying type - int.
I send data via post request, to create an ad. It looks like so:
POST http://localhost:...
1
vote
2
answers
943
views
How to type-level assert a type is not any?
I'm using a type-level Assert function to make assertions about the type-inferencing in my code. However, I'm not able to make any assertions about a type not being any.
type Assert<A extends ...
-1
votes
1
answer
129
views
how to get the asserted value in Julia?
struct MyType
end
struct MyType2
attr::MyType
end
My question is: if there is anyway to get attr within MyType. I know there is subtypes() that gives all subtypes of a type, I need something like ...
1
vote
1
answer
671
views
Typescript: Assert unknown input has type Pick<ConcreteType, subset of keys of ConcreteType> for specified keys
When trying to create a generic function to test if an unknown input is a subset of a known object type I run into trouble with Typescript. I want to specify which keys should be present and assert ...
5
votes
3
answers
650
views
How to hint the type of a function I do not control?
When parsing a JSON-formatted string I get a linter error:
let mqttMessage = JSON.parse(message.toString())
// ESLint: Unsafe assignment of an `any` value. (@typescript-eslint/no-unsafe-assignment)
...
2
votes
1
answer
929
views
Stricter type assertion in Typescript
So lets's say I have
declare function doSomething(...args: any[]): any
interface Example {
a: number
b: number
}
doSomething({a: 2, b: 1, c: 10} as Example)
This does not report an error as ...
3
votes
2
answers
1k
views
What's the best way to use a type assertion with destructuring assignment?
I have some code using destructuring assignment as follows:
const { values: project, setValues, submitForm } = useFormikContext();
Per the TypeScript type assertion documentation I'd like to use the ...