logo
down
shadow

How to make a generic type argument required in typescript?


How to make a generic type argument required in typescript?

By : Yehya A Ibraheem
Date : November 22 2020, 07:01 PM
Hope this helps See this open suggestion. The best approach I know of is to let T default to never as you did (assuming that never is not a valid type argument for T) and define the type of one of the parameters to the function so that (1) if T is specified as non-never, then the parameter has the type you actually want, and (2) if T is allowed to default to never, then the parameter has some dummy type that will generate an error because it doesn't match the argument type.
The tricky part is that if a caller sets T to some in-scope type variable U of its own, we want to allow the call even though TypeScript cannot rule out that U could be never. To handle that case, we use a helper type IfDefinitelyNever that abuses the simplification behavior of indexed access types to distinguish a definite never from a type variable. The special G ("gate") parameter is needed to prevent the call from IfDefinitelyNever from prematurely evaluating to its false branch in the signature of the function itself.
code :
type RequestType =
  | 'foo'
  | 'bar'
  | 'baz'

interface SomeRequest {
  id: string
  type: RequestType
  sessionId: string
  bucket: string
  params: Array<any>
}

type ResponseResult = string | number | boolean

const ERROR_INTERFACE_DUMMY = Symbol();
interface Type_parameter_T_is_required {
  [ERROR_INTERFACE_DUMMY]: never;
}
interface Do_not_mess_with_this_type_parameter {
  [ERROR_INTERFACE_DUMMY]: never;
}
type IfDefinitelyNever<X, A, B, G extends Do_not_mess_with_this_type_parameter> =
  ("good" | G) extends {[P in keyof X]: "good"}[keyof X] ? B : ([X] extends [never] ? A : B);

async function sendWorkRequest<T extends ResponseResult = never,
  G extends Do_not_mess_with_this_type_parameter = never>(
  type: RequestType & IfDefinitelyNever<T, Type_parameter_T_is_required, unknown, G>,
  ...params
): Promise<T> {
  await this.readyDeferred.promise

  const request: SomeRequest = {
    id: 'abc',
    bucket: 'bucket',
    type,
    sessionId: 'some session id',
    params: [1,'two',3],
  }
  const p = new Promise<T>(() => {})

  this.requests[request.id] = p
  this.worker.postMessage(request)
  return p
}


// DOESN'T WORK
async function test1() {
  // Error: Argument of type '"foo"' is not assignable to parameter of type
  // '("foo" & Type_parameter_T_is_required) |
  // ("bar" & Type_parameter_T_is_required) |
  // ("baz" & Type_parameter_T_is_required)'.
  const result = await sendWorkRequest('foo')
  result.split('')
}

test1()

// WORKS
async function test2() {
  const result = await sendWorkRequest<string>('foo')
  result.split('')
}

test2()

// ALSO WORKS
async function test3<U extends ResponseResult>() {
  const result = await sendWorkRequest<U>('foo')
}

test3()


Share : facebook icon twitter icon
How to not specify the type argument in a generic method when the required argument is null?

How to not specify the type argument in a generic method when the required argument is null?


By : Ricardo
Date : March 29 2020, 07:55 AM
Hope this helps You can not, cause that is a signature of your method.
You can create another method, which has no any generic arguments, so you will be able to call it like:
code :
var request = CreateRequest();
Typescript generic functions not working as expected - parameter containing another generic type than required, compiles

Typescript generic functions not working as expected - parameter containing another generic type than required, compiles


By : Fabian Grutsch
Date : March 29 2020, 07:55 AM
To fix this issue I am trying to develop simple event bus class in Typescript, where it will be possible to publish events and subscribe to them. It will be nice to have binding between published topic and the interface of data published. I have tried to achieve this using function and class generics, however some of my test cases are not working as expected (in a way that the lines I would expect to fail are compiled OK). I have also added example from: https://www.typescriptlang.org/docs/handbook/generics.html , which works as expected. In real-world situation I am planning to have instances of topics stored somewhere as singletons. , Here:
code :
class Topic<A> {}
class Topic<A> { abc: A; }
How to make function argument that is generic object consuming two functions with one type or void in Typescript

How to make function argument that is generic object consuming two functions with one type or void in Typescript


By : jerrolbrooks
Date : March 29 2020, 07:55 AM
help you fix your problem You can use union types:
code :
type Matcher<T, U> = {
    First: (arg: T) => U;
    Second: () => U | void
};
match<U>(matcher: Matcher<T, U>): U | void {
    return this.value
        ? matcher.First(this.value)
        : matcher.Second();
}
type Matcher<T, U> = {
    First: (arg: T) => U;
    Second: () => U;
};

type MatcherOne<T, U> = {
    First: (arg: T) => void;
    Second: () => U;
};

type MatcherTwo<T, U> = {
    First: (arg: T) => U;
    Second: () => void;
};

class Main<T> {
    constructor(private value: T) { }

    match<U>(matcher: Matcher<T, U>): U;
    match<U>(matcher: MatcherOne<T, U>): U | void;
    match<U>(matcher: MatcherTwo<T, U>): U | void;
    match<U>(matcher: Matcher<T, U> | MatcherOne<T, U> | MatcherTwo<T, U>): U | void {
        return this.value
            ? matcher.First(this.value)
            : matcher.Second();
    }
}
Typescript: make optional prop required if generic type is set

Typescript: make optional prop required if generic type is set


By : abhzoo
Date : March 29 2020, 07:55 AM
To fix this issue I'm not sure what your use case is, but if you can use a type alias instead of an interface, then you could define Foobar to be something like:
code :
type Foobar<T = never> = {
  foo: string;
} & ([T] extends [never] ? { bar?: any } : { bar: T });
const one: Foobar = { foo: "foo" }; // bar is not required here
const two: Foobar<number> = { foo: "foo", bar: 123 }; // `bar` is required here
TypeScript: How to make an optional second argument required based on the value of the first argument

TypeScript: How to make an optional second argument required based on the value of the first argument


By : Ralitza Delcheva
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Say I have a function that takes 2 args, and depending on the value of the first arg, the second arg may or may not be required. , You can use multiple overloads:
code :
function calculate(item: 'icon'): void
function calculate(item: 'category', state: IState): void
function calculate(item: 'icon' | 'category', state?: IState): void {

    if (item === 'icon') {
        // code in which I don't need to access anything in state
    } 

    if (item === 'category' && state) {
        // code in which I do need to access state
    }

}
calculate("icon")
calculate("category") //error
Related Posts Related Posts :
  • How to map DTO using interfaces in typescript?
  • Typescript: Define type as any but function
  • Typescript type safe HTTP post not really type safe
  • Need to click twice in KeyboardAvoidingView even when keyboardshouldpersisttaps is always
  • Typescript interface with keys of Generic
  • Nuxt custom plugin exports is not defined
  • TypeGraphQL use TypeORM's findAndCount method
  • 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
  • Typescript: Create object with same keys but different values
  • ServiceStack - Cannot get headers from in Typescript client ResponseFilter
  • Object.entries(qs).forEach(...) - resolve lambda ignoring type annotations
  • Accessing generics from inherited type
  • Deriving TypeScript interface from object literal
  • How to declare default-function for a class?
  • How to allow partial TypeScript types when mocking functions - Jest, TypeScript
  • Use an object as a map's key in the value
  • How can I ignore operating system font in react-native?
  • 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
  • Is function () { this.array = [newElem, ...array] } pure?
  • Understanding .tsconfig file
  • Compare two interfaces at runtime
  • Cant get variable in data
  • TypeScript inferencing with process.exit
  • Using the keys of an object literal as a Typescript type?
  • Retrieve current value of an observable
  • TypeScript: Declaring a callable type as a class method type
  • TestCafe - Checking if the hyperlink is working - redirection to an external email provider
  • Typescript, from us currency to es currency
  • How to properly define global enum in Typescript
  • Protractor typescript Error: WebDriverError: java.net.ConnectException: Connection refused: connect while selecting valu
  • How can I write extension for generic class in typescript as getter
  • TSLint: ordered-imports configuration
  • Module.exports with es6 import for webpack.config.ts in typescript
  • How can I find where TS type is defined in my app?
  • Using externally defined component with Vue and TypeScript class decorator syntax
  • typescript multiple generic cannot infered properly
  • Typescript switch case confusing compiler
  • Type guard with complement in false branch
  • Manually widen type
  • How do I type for arrays with ordered types of unknown length?
  • could be instantiated with a different subtype of constraint 'object'
  • Fix "Continue without scanning the task output" in Visual Studio Code
  • Typing declaration disambiguate Object or Function
  • TypeScript dynamically derived fields from another type
  • How can I create a generic type for a dynamic generated object created from an array
  • Why is typescript upset about comparing to undefined?
  • Nested queries in Apollo Server
  • How to run TypeScript from local directory instead of global
  • Typescript gives different errors in vscode than through webpack
  • Switching based on object type
  • winston custom transport with typescript
  • Enforce explicit function return type annotations?
  • How to match nested Keys in Typescript
  • Typescript allow extension of AxiosConfig
  • Can one represent indexable signatures in io-ts
  • Why won't TS let me index into a compatible object type?
  • Cannot find module that is defined in tsconfig `paths`
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk