Distinguish optional and nullable in all JavaScript languages

This commit is contained in:
Mark Probst 2018-04-05 22:10:17 -07:00
Родитель 184bd884b2
Коммит 3bf4cd848e
2 изменённых файлов: 11 добавлений и 13 удалений

Просмотреть файл

@ -162,10 +162,11 @@ export class JavaScriptRenderer extends ConvenienceRenderer {
};
typeMapTypeForProperty(p: ClassProperty): Sourcelike {
if (!p.isOptional || p.type.isNullable) {
return this.typeMapTypeFor(p.type);
const typeMap = this.typeMapTypeFor(p.type);
if (!p.isOptional) {
return typeMap;
}
return ["u(null, ", this.typeMapTypeFor(p.type), ")"];
return ["u(undefined, ", typeMap, ")"];
}
emitBlock = (source: Sourcelike, end: string, emit: () => void) => {
@ -258,7 +259,7 @@ ${this.castFunctionLine} {
function isValid(typ${anyAnnotation}, val${anyAnnotation})${booleanAnnotation} {
if (typ === undefined) return true;
if (typ === null) return val === null || val === undefined;
if (typ === null) return val === null;
return typ.isUnion ? isValidUnion(typ.typs, val)
: typ.isArray ? isValidArray(typ.typ, val)
: typ.isMap ? isValidMap(typ.typ, val)
@ -273,7 +274,7 @@ function isValidPrimitive(typ${stringAnnotation}, val${anyAnnotation}) {
function isValidUnion(typs${anyArrayAnnotation}, val${anyAnnotation})${booleanAnnotation} {
// val must validate against one typ in typs
return typs.find(typ => isValid(typ, val)) !== undefined;
return typs.some(typ => isValid(typ, val));
}
function isValidEnum(enumName${stringAnnotation}, val${anyAnnotation})${booleanAnnotation} {

Просмотреть файл

@ -20,6 +20,10 @@ export abstract class TypeScriptFlowBaseTargetLanguage extends JavaScriptTargetL
return [this._justTypes, this._declareUnions, this.runtimeTypecheck];
}
get supportsOptionalClassProperties(): boolean {
return true;
}
protected abstract get rendererClass(): new (
targetLanguage: TargetLanguage,
graph: TypeGraph,
@ -99,14 +103,7 @@ export abstract class TypeScriptFlowBaseRenderer extends JavaScriptRenderer {
protected emitClassBlockBody(c: ClassType): void {
this.emitPropertyTable(c, (name, _jsonName, p) => {
const t = p.type;
let nullable = t instanceof UnionType ? nullableFromUnion(t) : null;
if (p.isOptional && nullable === null) {
nullable = t;
}
return [
[name, nullable !== null ? "?" : "", ": "],
[this.sourceFor(nullable !== null ? nullable : t).source, ";"]
];
return [[name, p.isOptional ? "?" : "", ": "], [this.sourceFor(t).source, ";"]];
});
}