2

I'm still new to typescript, but I'm trying to pass a custom type to a function. I'm avoiding using "any" for this case, here is my example.

interface ReturnObj<T> {
  returnObj: T | null
}

const createResultObj = (
    isSuccessful: boolean = false,
    returnObj: ReturnObj = null,
    errors: AppError | null = null,
    statusCode: number = 500
   ): Result => {
return {
       isSuccessful,
       returnObj,
       errors,
       statusCode
     }
}

Naturally, this is returning an error with Generic type 'ReturnObj<T>' requires 1 type argument(s). but I'm not sure how to fill this part in so that I can call in this function and include the type if something exists in the returnObj.

1 Answer 1

3

All you need to is give a generic parameter to your function like below:

interface ReturnObj<T> {
  returnObj: T | null
}

type AppError = {} | null
type Result<T extends unknown> = {
  isSuccessful: boolean,
  returnObj: ReturnObj<T> | null,
  errors: AppError,
  statusCode: number
}

const createResultObj = <T extends unknown>(
  isSuccessful: boolean = false,
  returnObj: ReturnObj<T> | null = null,
  errors: AppError = null,
  statusCode: number = 500
): Result<T> => {
  return {
    isSuccessful,
    returnObj,
    errors,
    statusCode
  }
}

type sth = { foo: string };
const s: sth = { foo: "bar" }
const returnS: ReturnObj<sth> = { returnObj: s }
const re = createResultObj(true, returnS, null, 200);
console.log(re);

Playground Link

Note: <T extends unknown> is an obligation because of arrow function usage see this

Sign up to request clarification or add additional context in comments.

1 Comment

ahhh that makes perfect sense, thank you. I wasn't sure how to define the Result type with the generic so this works out perfectly. Appreciate the explanation and resource.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.