Simplified JSX contextual typing code and added support for contextually typing string literal attribute initializers.

This commit is contained in:
Daniel Rosenwasser 2015-12-23 17:10:16 -08:00
parent 4dc85dcbd6
commit a0ef319f5d

View file

@ -7464,24 +7464,22 @@ namespace ts {
return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined;
} }
function getContextualTypeForJsxExpression(expr: JsxExpression | JsxSpreadAttribute): Type { function getContextualTypeForJsxAttribute(attribute: JsxAttribute | JsxSpreadAttribute) {
// Contextual type only applies to JSX expressions that are in attribute assignments (not in 'Children' positions) const kind = attribute.kind;
if (expr.parent.kind === SyntaxKind.JsxAttribute) { const jsxElement = attribute.parent as JsxOpeningLikeElement;
const attrib = <JsxAttribute>expr.parent; const attrsType = getJsxElementAttributesType(jsxElement);
const attrsType = getJsxElementAttributesType(<JsxOpeningLikeElement>attrib.parent);
if (attribute.kind === SyntaxKind.JsxAttribute) {
if (!attrsType || isTypeAny(attrsType)) { if (!attrsType || isTypeAny(attrsType)) {
return undefined; return undefined;
} }
else { return getTypeOfPropertyOfType(attrsType, (attribute as JsxAttribute).name.text);
return getTypeOfPropertyOfType(attrsType, attrib.name.text); }
} else if (attribute.kind === SyntaxKind.JsxSpreadAttribute) {
return attrsType;
} }
if (expr.kind === SyntaxKind.JsxSpreadAttribute) { Debug.fail(`Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[${kind}]`);
return getJsxElementAttributesType(<JsxOpeningLikeElement>expr.parent);
}
return undefined;
} }
// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
@ -7549,8 +7547,10 @@ namespace ts {
case SyntaxKind.ParenthesizedExpression: case SyntaxKind.ParenthesizedExpression:
return getContextualType(<ParenthesizedExpression>parent); return getContextualType(<ParenthesizedExpression>parent);
case SyntaxKind.JsxExpression: case SyntaxKind.JsxExpression:
return getContextualType(<JsxExpression>parent);
case SyntaxKind.JsxAttribute:
case SyntaxKind.JsxSpreadAttribute: case SyntaxKind.JsxSpreadAttribute:
return getContextualTypeForJsxExpression(<JsxExpression>parent); return getContextualTypeForJsxAttribute(<JsxAttribute | JsxSpreadAttribute>parent);
} }
return undefined; return undefined;
} }