假设我有以下包含key1
和key2
的地图:
Map<String, bool> _map = {
'dog': true,
'cat': true
};
现在,我想强制Dart只允许某些键。在Typescript中,我可以做类似的事情:
enum AvailableKeysEnum {
Dog = 'dog',
Cat = 'cat'
}
interface AvailableKeys {
[key in AvailableKeysEnum]: boolean;
}
const availableKeys: AvailableKeys = {
'dog': true, // Allowed
'cat': true, // Allowed
'dolphin': true // Denied
}
我的问题是,如何强制Dart只允许某些键?
答案 0 :(得分:1)
如果我理解正确(我不知道TypeScript)
Dart没有关键约束,因此必须扩展Map并实现这些约束。这是代码。
import 'dart:collection';
class InvalidKeyError<K> extends Error {
final Object key;
final Set<K> keys;
InvalidKeyError(this.key, this.keys);
@override
String toString() => "InvalidKeyError: $key not found in $keys";
}
class SpecialMap<K, V> extends MapMixin<K, V> {
final Set<K> availableKeys;
final Map<K, V> _map = {};
SpecialMap(this.availableKeys) : assert(availableKeys != null);
@override
Iterable<K> get keys => _map.keys;
@override
void clear() => _map.clear();
@override
V remove(Object key) => _map.remove(key);
@override
V operator [](Object key) => availableKeys.contains(key)
? _map[key]
: throw InvalidKeyError(key, availableKeys);
@override
operator []=(K key, V value) => availableKeys.contains(key)
? _map[key] = value
: throw InvalidKeyError(key, availableKeys);
}
void main() {
final availableKeys = {"cat", "dog"};
final map = SpecialMap<String, bool>(availableKeys);
map["cat"] = true;
map["dog"] = true;
map["anything else"] = false; //will throw InvalidKeyError at runtime
}
尽管您可以根据需要简单地限制类型。像这样的东西。
enum Keys {cat, dog}
void main(){
final Map<Keys, bool> map = {};
map[Keys.cat] = true;
map[Keys.dog] = true;
map["any other type"] = false; //complie time error
}