The concept of a conditional type should encompass smart properties, and I sought assistance from @jcalz in the previous iteration of this query. Even though that issue was resolved, I am still unable to achieve the level of typing strictness I desire. The final line below is expected to raise an error:
interface Props<T, S extends boolean = boolean> {
value: T;
isString: S;
submit: S extends true ? (arg: string) => void : (arg: T & {}) => void;
}
interface FalseProps<T> {
value: T;
isString: false;
submit: (arg: T & {}) => void;
}
interface TrueProps<T> {
value: T;
isString: true;
submit: (arg: string) => void;
}
function fancyFunction<T>(props: Props<T>): void
function fancyFunction<T>(props: TrueProps<T> | FalseProps<T>): void {
if (props.isString === true) {
props.submit('return a string');
} else if (props.isString === false) {
props.submit(props.value);
}
}
const args1 = {
value: 2,
isString: true,
submit: (arg: string) => console.log(arg),
};
fancyFunction(args1);
const args2 = {
value: { id: 2 },
isString: false,
submit: (arg: { id: number }) => console.log(arg),
};
fancyFunction(args2);
const args3 = {
value: { id: 2 },
isString: false,
submit: (arg: string) => console.log(arg),
};
fancyFunction(args3);
You can access the TypeScript code here.