Typescript - make an optional property required when another property is present

不羁岁月 提交于 2021-02-09 10:33:06

问题


I have proptypes shown below

interface Props {
resource: string;
create?: boolean;
route?: string;
}

As can be seen above, create and route are optional props. However, I would like to implement the types such that if create prop is present then route must now be required. Anyone have any ideas how to do this?


回答1:


You should group these props and make that grouped prop optional as

interface RouteProps{
create: boolean;
route: string;
}

interface Props {
resource: string;
routeInfo?: RouteProps;
}



回答2:


although I like @DevLoverUmar 's solution more. You actually have the option to do something like this with typescript:

this might be what you re looking for. But you would have to explicitly set TArgs<true>

type TArgs<T extends boolean> = {
   a: T,
   b: string,
   c: T extends true ? string : null
 }

Example of how it could look with a factory function:

type TArgs<T extends true | false> = {
    a: T,
    c?: T extends true ? string : null
}

const argsFactory = <T extends boolean>(a: T, c: T extends true ? string : null): TArgs<T> => {
    return {
        a,
        c
    }
}

// Works
argsFactory(true, "string");
argsFactory(false, null);

// Doesnt Work
argsFactory(false, "some String");
argsFactory(true, null)



回答3:


You can split it into a union of two types and use create with a literal type:

type Props = {
  resource: string;
  create?: false;
  route?: string
} | {
  resource: string;
  create: true;
  route: string;
}


来源:https://stackoverflow.com/questions/64649356/typescript-make-an-optional-property-required-when-another-property-is-present

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!