1

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.

LTFoReal
  • 377
  • 5
  • 20

1 Answers1

1

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

Eldar
  • 9,781
  • 2
  • 10
  • 35
  • 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. – LTFoReal Sep 22 '20 at 20:00