gpt4 book ai didi

javascript - Flow 中所有键具有相同类型的对象

转载 作者:行者123 更新时间:2023-11-29 23:58:26 26 4
gpt4 key购买 nike

我目前正在比较 Google Closure CompilerFlow就表现力而言,静态类型检查器。我知道如何在 Closure 中而不是在 Flow 中做的一件事是表达一组具有相同类型的命名对象。在 Closure 中可以使用 the @enum annotation为此。

/** @enum {function(number):number} */
const unaryFunctions = {
sin: Math.sin,
cos: Math.cos,
square: function(x) { return x*x; },
};

有没有办法使用 Flow 做这样的事情?我想我可以使用 ES6 字典而不是普通对象,但如果交叉编译为 ES5,那将带来相当大的开销。我认为像这样的结构看起来很地道,所以我很惊讶我在文档中找不到匹配的类型描述。

最佳答案

你可以这样做:

const unaryFunctions: { ['sin'|'cos'|'square']: (number) => number } = {
sin: Math.sin,
cos: Math.cos,
square: function(x) { return x*x; },
};

如果不想重复key,可以稍微重写一下:

const unaryFunctions_ = {
sin: Math.sin,
cos: Math.cos,
square: function(x) { return x*x; },
};

const unaryFunctions: { [$Keys<typeof unaryFunctions_>]: (number) => number } = unaryFunctions_;

关于javascript - Flow 中所有键具有相同类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41165290/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com