branperr
branperr

Reputation: 514

Is it possible to create subtypes in typescript?

Sorry if this this has been answered elsewhere, I wasn't exactly sure the best way to query for the question.

Is it possible to create types in TypeScript that index or something to a different type? For example:

const addUserAction: Actions.User.Add = ....
const removeUserAction: Actions.User.Remove = ...

Upvotes: 1

Views: 1386

Answers (2)

Gray
Gray

Reputation: 16

Yes, you can use indexed access to your types. For example:

interface Actions {
    User: {
        Add: () => void;
        Remove: () => void;
    }
}

const addUserAction: Actions['User']['Add'] = () => null;
const removeUserAction: Actions['User']['Remove'] = () => null;

I think this link should help a little more.

Upvotes: 0

Marco Nisi
Marco Nisi

Reputation: 1251

Yes, if you have a type defined for example:

interface Actions {
  User: {
    Add: string
  }
}

You can use Actions['User'] to address the User type.

Upvotes: 1

Related Questions