简体   繁体   中英

How to make property optional when using ReturnType<>

I have this:

const getDefaultState = () => ({
  mainNotifMessage: '(unknown message)',
  notifDetails: '(unknown notification details)',
  severity: 'info' as 'info' | 'error' | 'warning' | 'success' | undefined,
  snackBarOpen: true,
  foo: Date.now() as any
});


export type NotifDefaultState = ReturnType<typeof getDefaultState>;

How can I tell t that I want the foo property to be optional? I tried this:

export type NotifDefaultState = ReturnType<typeof getDefaultState> & {ts?: any};

but no dice.

You go "backwards" and loosen a type. Since you are creating the type from a concrete instance that has the key, TypeScript infers that the key must be present.

You will have to create an interface and export that.

TypeScript doesn't have any built-in support for programmatically altering modifiers like ? or readonly on individual keys of an object type; see microsoft/TypeScript#32562 for a feature request. Until such things are implemented, you can build something close yourself using the utility types Pick and Omit , and an intersection . The following implementation of SelectivePartial uses a trick with conditional type inference to make the final displayed type a single object and not an ugly intersection:

type SelectivePartial<T, K extends keyof T> = Partial<Pick<T, K>> & Omit<T, K> extends infer O ?
    { [P in keyof O]: O[P] } : never;

Then your NotifDefaultState could be defined like this:

export type NotifDefaultState = SelectivePartial<ReturnType<typeof getDefaultState>, "foo">;

/* type NotifDefaultState = {
    foo?: any;
    mainNotifMessage: string;
    notifDetails: string;
    severity: "info" | "error" | "warning" | "success" | undefined;
    snackBarOpen: boolean;
} */

Okay, hope that helps; good luck!

Playground link to code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM