Skip to content

Commit

Permalink
fix: Expand index types correctly (#369)
Browse files Browse the repository at this point in the history
  • Loading branch information
thchia authored and danez committed Jul 14, 2019
1 parent 53a7a55 commit c1dce84
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/utils/__tests__/getTSType-test.js
Expand Up @@ -315,6 +315,38 @@ describe('getTSType', () => {
});
});

it('detects indexed access', () => {
const typePath = statement(`
var x: A["x"] = 2;
interface A { x: string };
`)
.get('declarations', 0)
.get('id')
.get('typeAnnotation')
.get('typeAnnotation');
expect(getTSType(typePath)).toEqual({
name: 'A["x"]',
raw: 'A["x"]',
});
});

it('resolves indexed access', () => {
const typePath = statement(`
var x: A["x"] = 2;
type A = { x: string };
`)
.get('declarations', 0)
.get('id')
.get('typeAnnotation')
.get('typeAnnotation');
expect(getTSType(typePath)).toEqual({
name: 'string',
raw: 'A["x"]',
});
});

it('resolves types in scope', () => {
const typePath = statement(`
var x: MyType = 2;
Expand Down
36 changes: 36 additions & 0 deletions src/utils/getTSType.js
Expand Up @@ -19,6 +19,7 @@ import getTypeParameters, {
import type {
FlowElementsType,
FlowFunctionArgumentType,
FlowLiteralType,
FlowObjectSignatureType,
FlowSimpleType,
FlowTypeDescriptor,
Expand Down Expand Up @@ -54,6 +55,7 @@ const namedTypes = {
TSTupleType: handleTSTupleType,
TSTypeQuery: handleTSTypeQuery,
TSTypeOperator: handleTSTypeOperator,
TSIndexedAccessType: handleTSIndexedAccessType,
};

function handleTSArrayType(
Expand Down Expand Up @@ -347,6 +349,40 @@ function handleTSTypeOperator(path: NodePath): ?FlowTypeDescriptor {
}
}

function handleTSIndexedAccessType(
path: NodePath,
typeParams: ?TypeParameters,
): FlowSimpleType {
// eslint-disable-next-line no-undef
const objectType: $Shape<FlowObjectSignatureType> = getTSTypeWithResolvedTypes(
path.get('objectType'),
typeParams,
);
// eslint-disable-next-line no-undef
const indexType: $Shape<FlowLiteralType> = getTSTypeWithResolvedTypes(
path.get('indexType'),
typeParams,
);

// We only get the signature if the objectType is a type (vs interface)
if (!objectType.signature)
return {
name: `${objectType.name}[${indexType.value.toString()}]`,
raw: printValue(path),
};
const resolvedType = objectType.signature.properties.find(p => {
// indexType.value = "'foo'"
return p.key === indexType.value.replace(/['"]+/g, '');
});
if (!resolvedType) {
return { name: 'unknown' };
}
return {
name: resolvedType.value.name,
raw: printValue(path),
};
}

let visitedTypes = {};

function getTSTypeWithResolvedTypes(
Expand Down

0 comments on commit c1dce84

Please sign in to comment.