Add support for $Keys

master
Paul Loyd 2017-11-29 10:00:39 +03:00
parent 08dc16aa4b
commit addbcb675b
3 changed files with 53 additions and 1 deletions

View File

@ -101,6 +101,28 @@ function unwrap(params: (?Type)[]): ?Type {
return type ? clone(type) : null;
}
function keys(params: (?Type)[], resolve: TypeId => Type): ?Type {
invariant(params.length === 1);
const [ref] = params;
invariant(ref && ref.kind === 'reference');
const record = resolve(ref.to);
invariant(record.kind === 'record');
const variants = wu(record.fields)
.pluck('name')
.map(name => ({kind: 'literal', value: name}))
.toArray();
return {
kind: 'union',
variants,
};
}
export default {
Object: object,
Buffer: buffer,
@ -112,7 +134,9 @@ export default {
$Shape: shape,
$ReadOnly: unwrap,
$Exact: unwrap, // TODO: another semantic for exact types?
// TODO: $Keys
$Keys: keys,
// TODO: $Values
// TODO: $Diff
// TODO: $All
// TODO: $Either
};

8
tests/samples/keys.js Normal file
View File

@ -0,0 +1,8 @@
type X = {
a: string,
b: boolean,
};
type Y = $Keys<X>;
export {Y};

20
tests/samples/keys.json Normal file
View File

@ -0,0 +1,20 @@
{
"types": [
{
"id": ["keys", "X"],
"kind": "record",
"fields": [
{"name": "a", "value": {"kind": "string"}, "required": true},
{"name": "b", "value": {"kind": "boolean"}, "required": true}
]
},
{
"id": ["keys", "Y"],
"kind": "union",
"variants": [
{"kind": "literal", "value": "a"},
{"kind": "literal", "value": "b"}
]
}
]
}