Skip to content

Commit ffec768

Browse files
committed
union and intersection types
1 parent f7227b1 commit ffec768

File tree

1 file changed

+43
-0
lines changed
  • packages/svelte/src/compiler/phases

1 file changed

+43
-0
lines changed

packages/svelte/src/compiler/phases/scope.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1480,6 +1480,43 @@ function get_global_keypath(node, scope) {
14801480
* @returns {any}
14811481
*/
14821482
function get_type_of_ts_node(node, scope) {
1483+
/**
1484+
* @param {any[]} types
1485+
* @returns {any[]}
1486+
*/
1487+
function intersect_types(types) {
1488+
if (types.includes(UNKNOWN)) return [UNKNOWN];
1489+
/** @type {any[]} */
1490+
let res = [];
1491+
if (
1492+
types.filter((type) => typeof type === 'number' || typeof type === 'bigint').length > 1 ||
1493+
(!types.some((type) => typeof type === 'number' || typeof type === 'bigint') &&
1494+
types.includes(NUMBER))
1495+
) {
1496+
res.push(NUMBER);
1497+
} else {
1498+
res.push(...types.filter((type) => typeof type === 'number' || typeof type === 'bigint'));
1499+
}
1500+
if (
1501+
types.filter((type) => typeof type === 'string').length > 1 ||
1502+
(!types.some((type) => typeof type === 'string') && types.includes(STRING))
1503+
) {
1504+
res.push(STRING);
1505+
} else {
1506+
res.push(...types.filter((type) => typeof type === 'string'));
1507+
}
1508+
if (
1509+
types.filter((type) => !['symbol', 'string', 'number', 'bigint'].includes(typeof type))
1510+
.length > 1
1511+
) {
1512+
res.push(UNKNOWN);
1513+
} else {
1514+
types.push(
1515+
...types.filter((type) => !['symbol', 'string', 'number', 'bigint'].includes(typeof type))
1516+
);
1517+
}
1518+
return res;
1519+
}
14831520
switch (node.type) {
14841521
case 'TypeAnnotation':
14851522
return get_type_of_ts_node(node.annotation, scope);
@@ -1488,6 +1525,12 @@ function get_type_of_ts_node(node, scope) {
14881525
get_type_of_ts_node(node.trueType, scope),
14891526
get_type_of_ts_node(node.falseType, scope)
14901527
].flat();
1528+
case 'TSUnionType':
1529+
//@ts-ignore
1530+
return node.types.map((type) => get_type_of_ts_node(type, scope)).flat();
1531+
case 'TSIntersectionType':
1532+
//@ts-ignore
1533+
return intersect_types(node.types.map((type) => get_type_of_ts_node(type, scope)).flat());
14911534
case 'TSBigIntKeyword':
14921535
case 'TSNumberKeyword':
14931536
return NUMBER;

0 commit comments

Comments
 (0)