打字稿界面期望一个数字道具小于另一个数字道具



是否有可能让 TypeScript 接口接受一个numberprop,该 prop 的值总是应该小于接口中另一个numberprop?

例如,如果我有一个numberOfFiles道具和一个currentFileIndex道具,我总是期望currentFileIndex道具小于numberOfFiles。我可以在我的界面中定义它吗?

大致如下:

interface IProps {
numberOfFiles: number;
currentFileIndex: number<less than numberOfFiles>;
}

如果不可能,这不是世界末日,但知道它是否是会很棒。

没有办法直接做到这一点,打字稿没有办法对这样的约束进行建模。

但是,您可以强制此界面的所有用户通过使用类似于此处显示的品牌类型来提前执行检查

interface IProps {
numberOfFiles: number;
currentFileIndex: number & { mustBeLessThenNumberOfFiles: true };
}
type Omit<T, TKeys extends keyof T> = Pick<T, Exclude<keyof T, TKeys>>
function createProps(p: Omit<IProps, 'currentFileIndex'> & {
currentFileIndex: number 
}) {
if(p.currentFileIndex > p.numberOfFiles) throw "Error!";
return p as IProps;
}
//ok
createProps({
numberOfFiles: 10,
currentFileIndex: 5
});
// compiles but with runtime error when props are created
createProps({
numberOfFiles: 10,
currentFileIndex: 15
});
// error
let p : IProps = {
numberOfFiles: 10,
currentFileIndex: 5 // error we did not make sure with a check 
}

最新更新