DTO\Reinforced.Typings 試用紀錄
C# DTO to TypeScript generator, MTT.
簡介
說明:You develop frontend applications with TypeScript and .NET Backend? You need Reinforced.Typings.
說明2: 支援用 MS Build 在編譯過程把 C# DTO 轉換成 TypeScript interface。一個檔案可有多個 DTO 類別。
試用紀錄
安裝
> NuGet\Install-Package Reinforced.Typings
設定檔 Reinforced.Typings.settings.xml
請參考 Reinforced.Typings.settings.xml 預設值與說明。下面是本例調整後的設定。
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<!-- 指定匯出檔案目標位置 -->
<RtTargetFile>$(ProjectDir)\YourProject.client\src\server-dto.ts</RtTargetFile>
<RtConfigurationMethod></RtConfigurationMethod>
<!-- 啟用:依 namespace 分割生成對映應目錄與檔案 -->
<RtDivideTypesAmongFiles>false</RtDivideTypesAmongFiles>
<!--
須與參數 RtDivideTypesAmongFiles 搭配。
依 namespace 分割生成對映應目錄與檔案:指定生成目標目錄。
-->
<RtTargetDirectory>$(ProjectDir)Scripts\MyApplication</RtTargetDirectory>
<RtBypassTypeScriptCompilation>false</RtBypassTypeScriptCompilation>
<RtDisable>false</RtDisable>
<RtSuppress>RTW0013;RTW0014</RtSuppress>
</PropertyGroup>
</Project>
設定 Reinforced.Typings 全域參數
參考文件
預設的全域參數在本例不合用,調整如下。
using Reinforced.Typings.Attributes;
//## Reinforced.Typings 全域設定說明
[assembly: TsGlobal(
CamelCaseForProperties = true, // 小駱駝命名法
UseModules = true, // 啟用 modules
DiscardNamespacesWhenUsingModules = true, // 需與參數 UseModules 搭配;不產生 "modules"。
ExportPureTypings = true // 生成純宣告檔 .d.ts。
)]
var builder = WebApplication.CreateBuilder(args);
[...略...]
試轉檔案
來源檔
using Reinforced.Typings.Attributes;
namespace YourProject.Server.DTO;
[TsInterface] //--- ※須掛上此屬性才會轉換成。
public record WeatherForecast
{
//---※手動指定轉換 type,因為 DateOnly → any 故手動指定。
[TsProperty(Type = "string")] //--- ※指定轉換的 type。
public DateOnly Date { get; set; } = default!;
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
[TsInterface] //--- ※須掛上此屬性才會轉換。
public record MyTestDto
{
//---※手動指定轉換 type,因為 DateTime → any 故手動指定。
[TsProperty(Type = "string")]
public DateTime TestDateTime { get; set; }
public string TestString { get; set; }
public decimal TestDecimal { get; set; }
public bool TestBool { get; set; }
}
轉換後
// This code was generated by a Reinforced.Typings tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
export interface IWeatherForecast
{
date: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
export interface IMyTestDto
{
testDateTime: string;
testString: string;
testDecimal: number;
testBool: boolean;
}
(EOF)
Last updated