C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#转TypeScript

浅谈熟悉C#如何转TypeScript

作者:向上的车轮

本文主要介绍了浅谈熟悉C#如何转TypeScript,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

✅相同点(你已掌握的优势)

特性说明
静态类型TS 和 C# 都支持变量、参数、返回值的类型标注(如 string, number ≈ string, int)。
类与面向对象class、interface、extends(继承)、implements(实现接口)语法高度相似。
泛型都用 <T>,如 List<T>(C#) ↔ Array<T> 或 T[](TS)。
访问修饰符public/private/protected 在 TS 中用于编译期检查(运行时无作用,但 IDE 支持好)。
async/await异步编程模型几乎一样:C# 用 Task<T>,TS 用 Promise<T>。

⚠️关键差异(需注意)

方面C#TypeScript
运行环境编译为 .NET IL,在 CLR 上运行编译为 JavaScript,在浏览器或 Node.js 中运行
类型系统强制、严格(编译失败即错误)可选 + 渐进式(可写纯 JS,但推荐全类型)
基础类型int, bool, DateTime 等基于 JS:number(无 int/float 区分)、boolean、string;无内置日期类型(用 Date 对象)
空值处理null + 可空类型 int?null 和 undefined 并存;开启 strictNullChecks 后类似 C# 可空引用
模块化namespace / 程序集ES 模块:import { x } from './file' / export(无 namespace)
变量声明int x = 1; 或 var x = 1;必须用 let / const:const x: number = 1;
函数定义int Add(int a, int b) => a + b;const add = (a: number, b: number): number => a + b;

🚀转型建议(3 步上手)

  1. 写法习惯调整

    • const/let 代替 var
    • import/export 组织代码
    • 函数多用箭头函数 () => {}
  2. 善用 TS 的“超能力”

    • 接口 (interface) 定义对象形状(比 C# 更灵活)
    • 联合类型:string | number
    • 类型推断强大,很多时候不用显式写类型
  3. 记住:TS ≠ 新语言,而是“带类型的 JS”

    • 所有 JS 语法都合法
    • 你的 C# 架构思维(SOLID、分层等)完全适用
    • 差别主要在标准库和运行时 API(比如发 HTTP 请求用 fetch 而不是 HttpClient

💡 一句话总结:

TypeScript = C# 的类型系统 + JavaScript 的灵活性 + 浏览器/Node.js 运行时。

你已具备 80% 的核心能力,只需适应 JS 生态和少量语法差异,就能高效开发!

C# 与 TypeScript 的典型代码对比

1.变量声明

// C#
string name = "Alice";
int age = 30;
var isActive = true; // 类型推断
// TypeScript
const name: string = "Alice";
let age: number = 30;
const isActive = true; // 类型自动推断为 boolean

✅ 建议:TS 中优先用 const(不可变)和 let(可变),避免 var

2.函数定义

// C#
public int Add(int a, int b)
{
    return a + b;
}

// 或表达式体
public int Multiply(int a, int b) => a * b;
// TypeScript
function add(a: number, b: number): number {
    return a + b;
}
// 或箭头函数(更常见)
const multiply = (a: number, b: number): number => a * b;
// 返回类型通常可省略(TS 能推断)
const subtract = (a: number, b: number) => a - b;

3.类与继承

// C#
public class Animal
{
    public string Name { get; set; }
    
    public Animal(string name) => Name = name;
    
    public virtual void Speak() => Console.WriteLine("...");
}

public class Dog : Animal
{
    public Dog(string name) : base(name) { }
    
    public override void Speak() => Console.WriteLine("Woof!");
}
// TypeScript
class Animal {
    constructor(public name: string) {} // 自动创建并赋值 this.name
    speak(): void {
        console.log("...");
    }
}
class Dog extends Animal {
    speak(): void {
        console.log("Woof!");
    }
}

✅ TS 的 constructor(public name: string) 是语法糖,等价于 C# 的自动属性初始化。

4.接口(Interface)

// C#
public interface IPerson
{
    string Name { get; set; }
    int Age { get; }
    void Greet();
}
// TypeScript
interface Person {
    name: string;
    readonly age: number; // 只读 ≈ C# 的 { get; }
    greet(): void;
}

💡 TS 接口用于描述对象形状,不限于类实现,也可用于普通对象:

const person: Person = { name: "Bob", age: 25, greet() { console.log("Hi"); } };

5.泛型(Generics)

// C#
public class Box<T>
{
    public T Value { get; set; }
    
    public Box(T value) => Value = value;
}

var numberBox = new Box<int>(42);
// TypeScript
class Box<T> {
    constructor(public value: T) {}
}
const numberBox = new Box<number>(42);
// 或让 TS 推断
const stringBox = new Box("hello");

6.异步编程

// C#
public async Task<string> FetchDataAsync()
{
    using var client = new HttpClient();
    return await client.GetStringAsync("https://api.example.com/data");
}
// TypeScript(浏览器或 Node.js 环境)
async function fetchData(): Promise<string> {
    const response = await fetch("https://api.example.com/data");
    return await response.text();
}
// 或使用 axios(需安装)
import axios from 'axios';
async function fetchData2(): Promise<string> {
    const res = await axios.get<string>("https://api.example.com/data");
    return res.data;
}

✅ 概念一致:async/await + 容器类型(Task<T> ↔ Promise<T>)

7.空值处理(启用 strict 模式)

// C#
string? maybeName = GetName(); // 可空引用类型(C# 8+)
if (maybeName != null)
    Console.WriteLine(maybeName.Length);
// TypeScript(tsconfig.json 中开启 "strictNullChecks": true)
function getName(): string | null {
    return Math.random() > 0.5 ? "Alice" : null;
}
const maybeName = getName();
if (maybeName !== null) {
    console.log(maybeName.length); // 安全访问
}

🔒 强烈建议在 tsconfig.json 中启用 strict: true,获得接近 C# 的空安全体验。

总结:你的 C# 经验可以直接迁移!

C# 概念TypeScript 对应
classclass(几乎一样)
interfaceinterface(更灵活)
List<T>T[] 或 Array<T>
Task<T>Promise<T>
namespace不用 → 改用 import/export
HttpClientfetch 或 axios

你缺的只是 JavaScript 运行时 API前端/Node.js 生态 的熟悉度,语言本身对你来说几乎没有学习曲线!

到此这篇关于浅谈熟悉C#如何转TypeScript的文章就介绍到这了,更多相关C#转TypeScript内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文