Ron
Ron

Reputation: 6755

In Typescript, how to let generic type default to nothing?

I am trying to define a type Result which has an optional Data type.

My current type definition is:

type Result<Data = void> = {
  tx: string,
  data: Data
}

But it has the following issues (line #2 is not passed):

const ret: Result<{userId: string}> = {tx: "123", data: {userId: "456"}} // it is GOOD!
const ret: Result = {tx: "123"} // it will complain missing data, how can we pass it?

Can anyone help? Thank you!

Upvotes: 2

Views: 144

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371193

void does not make sense in a context where an expression value is expected - void is like saying there is no value at all (not undefined or null, but that there isn't any value associated with it). So typing a property value as void doesn't make sense, just like

const foo: void = <anything>

doesn't make sense - unless you explicitly use something that returns a void type, which is really weird (better not to pass it at all).

One approach is to use a conditional object type:

type Result<Data = void> = void extends Data
  ? {
    tx: string
  }
  : {
    tx: string,
    data: Data
  };

const ret: Result<{ userId: string }> = { tx: "123", data: { userId: "456" } } // Good
const ret2: Result = { tx: "123" } // Good
const ret3: Result = { tx: "123", data: 'foo' } // Bad

Upvotes: 2

Related Questions