3 回答

TA貢獻1887條經驗 獲得超5個贊
您應該對這些道具進行分組,并將分組的道具設為可選
interface RouteProps{
create: boolean;
route: string;
}
interface Props {
resource: string;
routeInfo?: RouteProps;
}

TA貢獻1846條經驗 獲得超7個贊
您可以將其拆分為兩種類型的聯合并create與文字類型一起使用:
type Props = {
resource: string;
create?: false;
route?: string
} | {
resource: string;
create: true;
route: string;
}

TA貢獻1865條經驗 獲得超7個贊
實際上,您可以選擇使用打字稿執行類似的操作:
這可能就是您正在尋找的。但你必須明確設置TArgs<true>
type TArgs<T extends boolean> = {
a: T,
b: string,
c: T extends true ? string : null
}
使用工廠函數的示例:
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)
添加回答
舉報