type check动态属性flowtype

时间:2017-12-05 10:46:46

标签: flowtype

我正在尝试向对象添加动态属性,并让流类型检查它们:

我的功能是这样的:

function defineStuff(obj:MyType, keys:string[]):??? {
    keys.forEach(function(key) {
        Object.defineProperty(obj, key, {get:function(){....}});
        obj["Add"+key] = function(value) {....};
        obj["Remove"+key] = function(value) {....};
    }
    return obj;
}

我希望能够做到这样的事情;

var obj : MyType = fetchMyObj();
defineStuff(obj, ["Thing", "OtherThing"]);
var thing = obj.Thing;
obj.AddOtherThing(10);

所有动态属性类型都是数字

是否有在流程中执行此操作的语法? (即如何填写???)

1 个答案:

答案 0 :(得分:0)

这适用于字典。

   
type MyType = {[key: string]: number};

// ...
function defineStuff(obj: MyType, keys:string[]): MyType {
    keys.forEach(function(key) {
        Object.defineProperty(obj, key, {get:function(){....}});

        // you can't have functions here, because you say that all values should be numbers
        // obj["Add"+key] = function(value) {....};
        // obj["Remove"+key] = function(value) {....};
    }
    return obj;
}

// ...

See docs