#What's wrong with this type?

7 messages · Page 1 of 1 (latest)

covert galleon
#

@fast hamlet You need to use generics if you want to relate a return type to an input type.

#

Doing typeof response doesn't work - resonse is string | number, so your callback type is essentially:

type Callback = (response: string | number) => Promise<GetReturnType<string | number>>;
fast hamlet
#

type ContainCallback = {
  callback: () => void
}

type GetReturnType<R> = R extends string ? ContainCallback : void;

type Callback = (response: string | number) => Promise<GetReturnType<typeof response>>;

function send(callback: Callback){}

send(async (response) => {
  if(typeof response === "string"){
    // i want client code to only return if the type is string, and expect it to be called
    const anotherCallback = () => {}
    return {
      callback: anotherCallback
    }
  }
  const anotherCallback2 = () => {

  }
  // I want this to cause error to prevent client to expect the callback will be called.
  return {
    callback: anotherCallback2
  }
})

#

this is why i need this, i just don't want the client code to return the callback expecting it's gonna get called

#

when the response code is non-string

covert galleon
#
type Callback<R extends string | number> = (response: R) => Promise<GetReturnType<R>>;
#

You can try this