public string GetTypeScript() { string result; if (BasicType != null) { result = BasicType; } else if (InterfaceType != null) { result = InterfaceType.TsName; } else if (EnumType != null) { result = EnumType.TsName; } else if (ArrayElementType != null) { result = "(" + ArrayElementType.GetTypeScript() + ")[]"; } else { throw new Exception(); } if (Nullable) { result += " | null"; } return(result); }
private TypeConverter getConverter(ApiTypeDesc type) { var key = type.GetTypeScript(); if (!_typeConverters.TryGetValue(key, out var converter)) { converter = new TypeConverter { ForType = type }; if (type.BasicType != null) { if (type.TypeMapper == null) { converter = null; } else { converter.WriteFunctionBody = (writer, toTypeScript) => { if (!toTypeScript) { writer.WriteLine($"return {type.TypeMapper.ConvertFromTypeScript("val")};"); } else { writer.WriteLine($"return {type.TypeMapper.ConvertToTypeScript("val")};"); } }; } } else if (type.EnumType != null) { // TODO: Flags converter = null; } else if (type.ArrayElementType != null) { var elConverter = getConverter(type.ArrayElementType); if (elConverter == null) { converter = null; } else { converter.UsesConverters.Add(elConverter); converter.WriteFunctionBody = (writer, toTypeScript) => { writer.WriteLine("for (let i = 0; i < val.length; i++)"); using (writer.Indent()) { writer.WriteLine("if (val[i])"); using (writer.Indent()) writer.WriteLine($"val[i] = this.{elConverter.FunctionName(toTypeScript)}(val[i]);"); } writer.WriteLine("return val;"); }; } } else if (type.InterfaceType != null) { var propConverters = type.InterfaceType.Properties.Select(p => new { prop = p, conv = getConverter(p.TsType) }).Where(x => x.conv != null).ToList(); if (propConverters.Count == 0) { converter = null; } else { foreach (var pc in propConverters) { converter.UsesConverters.Add(pc.conv); } converter.WriteFunctionBody = (writer, toTypeScript) => { foreach (var pc in propConverters) { writer.WriteLine($"if (val.{pc.prop.TsName})"); using (writer.Indent()) writer.WriteLine($"val.{pc.prop.TsName} = this.{pc.conv.FunctionName(toTypeScript)}(val.{pc.prop.TsName});"); } writer.WriteLine("return val;"); }; } } else { throw new Exception(); } } _typeConverters[key] = converter; return(converter); }