将接口的属性值限制为对象的值之一

时间:2019-04-21 19:06:30

标签: typescript types interface

如果接口类型为IExpression的对象具有不是expressions.null.property值之一的expressions.video.propertyPROPERTIES值,我希望TypeScript引发错误。 / p>

我有这个对象:

const PROPERTIES =  {
    ANCHOR_POINT: 'anchorPoint',
    POSITION: 'position',
    X_POSITION: 'xPosition',
    Y_POSITION: 'yPosition',
    Z_POSITION: 'zPosition',
    SCALE: 'scale',
    ORIENTATION: 'orientation',
    ROTATION: 'rotation',
    X_ROTATION: 'xRotation',
    Y_ROTATION: 'yRotation',
    Z_ROTATION: 'zRotation',
    OPACITY: 'opacity',
};

我想将IExpression.expressions.null.property限制为PROPERTIES值之一。

这是我要使其正常工作的方式:

type NULL_OR_VIDEO = "null" | "video";

interface IExpression {
    name: string;
    targets: FILE[];
    expressions: {
        [value in NULL_OR_VIDEO]: {
            property: PROPERTIES;
            expressionText: string;
        }
    }
}

虽然它抛出错误。我知道我可以这样做:

interface IExpression {
    name: string;
    targets: FILE[];
    expressions: {
        [value in NULL_OR_VIDEO]: {
            property: 'rotation' | 'xRotation'| 'opacity' ...
            expressionText: string;
        }
    }
}

但是我不想。

1 个答案:

答案 0 :(得分:0)

我将PROPERTIES转换为枚举:

enum PROPERTIES  {
    ANCHOR_POINT = 'anchorPoint',
    POSITION = 'position',
    X_POSITION = 'xPosition',
    Y_POSITION = 'yPosition',
    Z_POSITION = 'zPosition',
    SCALE = 'scale',
    ORIENTATION = 'orientation',
    ROTATION = 'rotation',
    X_ROTATION = 'xRotation',
    Y_ROTATION = 'yRotation',
    Z_ROTATION = 'zRotation',
    OPACITY = 'opacity',
};

现在可以这样工作:

interface IExpression {
    name: string;
    targets: FILE[];
    expressions: {
        [value in NULL_OR_VIDEO]?: {
            property: PROPERTIES;
            expressionText: string;
        }
    }
}