Generic function argument affecting the return type with default implementation

Generic function argument affecting the return type with default implementation

Content Index :

Generic function argument affecting the return type with default implementation
Tag : typescript , By : silvervino
Date : November 28 2020, 04:01 AM

To fix the issue you can do You could do this either with overloads or conditional types. Differing numbers of parameters seems to work better with overloads, like this:
function maybeTransform(): "abc";
function maybeTransform<R>(transform: (arg: string)=>R): R;
function maybeTransform(transform?: (arg: string)=>any) {
  const myString = "abc";
  return transform ? transform(myString) : myString;
const x = maybeTransform(); // "abc"
const y = maybeTransform((x: string) => x.length); // number
function maybeTransform<F extends undefined | ((arg: string) => any) = undefined>(
  transform?: F
): F extends (arg: string) => infer R ? R : "abc" {
  const myString = "abc";
  return transform ? transform(myString) : myString;
const x = maybeTransform(); // "abc"
const y = maybeTransform((x: string) => x.length); // number
const whoKnows = Math.random()<0.5 ? undefined : ((x: string)=>x.length);
const xOrY = maybeTransform(whoKnows);

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Is it possible to return generic type from argument passed to a function

Tag : typescript , By : Giles
Date : March 29 2020, 07:55 AM
hop of those help? Use can use a conditional type to extract the type argument from EVENT. Type parameters are not inferred one based on another usually, and you end up with the narrowest possible type (in this case {})
    constructor(public requestPayload: REQUEST_PAYLOAD) { }

    // this method was only created for the sake of showing response1 type example
    public return_RESPONSE_PAYLOAD_type(): RESPONSE_PAYLOAD {
        return null;

type GetUserInfoRequest = { userId: number };
type GetUserInfoResponse = { username: string; age: number };

class GetUserInfoEvent extends BaseEvent<
    > { }
// Conditional type to extract the response payload type:
type RESPONSE_PAYLOAD<T extends BaseEvent<any, any>> = T extends BaseEvent<any, infer U> ? U : never; 
const emit = async <
    EVENT extends BaseEvent<any, any>
    event: EVENT
    // some stuff will be done there - for the sake of example it was removed
    return null;

    // return event.return_RESPONSE_PAYLOAD_type(); // doesn't work aswell

const main = async () => {
    const event = new GetUserInfoEvent({ userId: 666 });
    const response1 = event.return_RESPONSE_PAYLOAD_type(); // type === { username: string; age: number; }
    const response2 = await emit(event); // is now GetUserInfoResponse

    response2.username //<-- ok
    response2.age //<-- ok


How do you provide a default argument for a generic function with type constraints?

Tag : swift , By : David
Date : March 29 2020, 07:55 AM
With these it helps The significant constraint is T: ExpressibleByStringLiteral. That's what allows something to be initialized from a string literal.
func doSomething<T: Collection>(value: T = "abc")
    where T.Element == Character, T: ExpressibleByStringLiteral {
    // ...
func doSomething<T: StringProtocol>(value: T) {

func doSomething() {
    doSomething(value: "abc")

Cannot convert return expression of generic protocol's function type implementation

Tag : ios , By : Ansari
Date : March 29 2020, 07:55 AM

How to get correct return type depending on the generic argument from a generic function

Tag : typescript , By : Dennizzz
Date : March 29 2020, 07:55 AM
I hope this helps . TypeScript currently lacks support in the type system for most higher kinded types, which is what you'd need to represent an operation on a generic function type. So the short answer is "you can't do this, sorry".
type T1 = { a: number };
const t1 = true as false || f1(null! as number);
type T1 = typeof t1; // {a: number}
type T1 = typeof f1(123);

Inferred generic function typechecks as a return type but not an argument type

Tag : haskell , By : Chaz
Date : January 02 2021, 06:48 AM
this one helps. I'm learning about SYB and rank n types, and came across a confusing case of what seems like the monomorphism restriction. , In your second snippet, op is actually not polymorphic.
shallowest p = let { op = (empty `mkQ` p) } in op
 types         values
 ↓             ↓
 x, a, f, ...; op :: x -> f a, ... |- op :: x -> f a
                                            monotype (no "forall")

 In English: "op has type (x -> f a) in the context consisting of type variables (x, a, f, ...) and values (op :: x -> f a, ...)"
     x, a, f |- (let op = ... in op) :: x -> f a
 ⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻ (generalization)
   |- (let op = .... in op) :: forall x a f. x -> f a
Related Posts Related QUESTIONS :
  • rxjs: Map adding field
  • How to use Mocha and Jest with TypeScript without conflicts?
  • Vue 2 + TypeScript: Avoid mutating Prop directly - in a class based component with vue-property-decorator
  • Use an object as a map's key in the value
  • How to allow partial TypeScript types when mocking functions - Jest, TypeScript
  • How to declare default-function for a class?
  • Deriving TypeScript interface from object literal
  • Accessing generics from inherited type
  • ServiceStack - Cannot get headers from in Typescript client ResponseFilter
  • Object.entries(qs).forEach(...) - resolve lambda ignoring type annotations
  • Typescript: Create object with same keys but different values
  • Defining a list of tuples with optional first and last elements
  • Error Message: "An interface can only extend an object type or intersection of object types with statically known m
  • Nuxt custom plugin exports is not defined
  • TypeGraphQL use TypeORM's findAndCount method
  • Typescript interface with keys of Generic
  • Need to click twice in KeyboardAvoidingView even when keyboardshouldpersisttaps is always
  • Typescript type safe HTTP post not really type safe
  • Typescript: Define type as any but function
  • How to map DTO using interfaces in typescript?
  • How to make a generic type argument required in typescript?
  • Get value of Observable<SomeObject> in an object
  • Typescript generics: Howto map array entries to object keys
  • How to restrict method argument to index number of tuple type?
  • How can we use Typescript with CodeceptJS for testing framework?
  • How to enable "error prevention only" in TSLint? (Disable style checks, etc.)
  • Working with typescript non-discriminated unions
  • how to limit keys of an object to a list of set strings in typescript
  • How to type a function so that its return type matches that of an array that is being returned?
  • Typescript not building in Container-based Azure Function App
  • Redeclare destructured variables in Typescript
  • Object literal which implements an interface which in turn uses a generic method
  • How to set a Type Literal on a widened type parameter (or prevent type widening)?
  • Correct type for a function that sets individual properties of an object?
  • What is bivariant parameter? ~ TypeScript
  • Typescript: “not assignable to parameter of type never” error
  • Typescript: prevent assignment of object with more properties than is specified in target interface
  • How to import constants from another file on TypeScript?
  • Typescript - Generic for deriving the same type but with no properties undefined
  • How to test refresh and expired token scenarios?
  • How to make reactive variables, like the data() in Vue? Vue+Typescript
  • Firebase Cloud Functions Returning Processed Data Using onCall
  • For an interface, what is the difference between these two way?
  • How to reduce type range
  • How to run migrations in a feathersjs typescript project?
  • Is there a way to select/set a theme through the VS Code extension API?
  • Open modal with images and selection on images in ionic 4?
  • Destructure in TS
  • How I "Run" a TypeScript file in WebStorm?
  • NUXT Using shared styles and scripts outside of project location
  • What does static mean in Typescript?
  • Unit testing with aws-cdk typescript
  • Typescript won't allow me to access object property
  • How to check if a string contains only white space or is empty in TypeScript?
  • Typescript Fetch API return Promise<T> or Promise<T[]>
  • Keep track of state in class instance
  • How to hint types for class methods that are dynamically created?
  • How to build a Typescript object using a functional compose style
  • Typescript: create union instead intersection when merging optional with required type
  • How to give exact type-information in return type without using "any" for a function that returns multiple dif
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com