熟悉C#如何转TypeScript?


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

特性 说明
静态类型 TS 和 C# 都支持变量、参数、返回值的类型标注(如 string, numberstring, int)。
类与面向对象 classinterfaceextends(继承)、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 区分)、booleanstring无内置日期类型 (用 Date 对象)
空值处理 null + 可空类型 int? nullundefined 并存;开启 strictNullChecks 后类似 C# 可空引用
模块化 namespace / 程序集 ES 模块import { x } from './file' / export(无 namespace
变量声明 int x = 1;var x = 1; 必须用 let / constconst 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. 变量声明

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

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


2. 函数定义

csharp 复制代码
// C#
public int Add(int a, int b)
{
    return a + b;
}

// 或表达式体
public int Multiply(int a, int b) => a * b;
typescript 复制代码
// 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. 类与继承

csharp 复制代码
// 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 复制代码
// 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)

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

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

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

5. 泛型(Generics)

csharp 复制代码
// C#
public class Box<T>
{
    public T Value { get; set; }
    
    public Box(T value) => Value = value;
}

var numberBox = new Box<int>(42);
typescript 复制代码
// TypeScript
class Box<T> {
    constructor(public value: T) {}
}

const numberBox = new Box<number>(42);
// 或让 TS 推断
const stringBox = new Box("hello");

6. 异步编程

csharp 复制代码
// C#
public async Task<string> FetchDataAsync()
{
    using var client = new HttpClient();
    return await client.GetStringAsync("https://api.example.com/data");
}
typescript 复制代码
// 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 模式)

csharp 复制代码
// C#
string? maybeName = GetName(); // 可空引用类型(C# 8+)
if (maybeName != null)
    Console.WriteLine(maybeName.Length);
typescript 复制代码
// 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 对应
class class(几乎一样)
interface interface(更灵活)
List<T> T[]Array<T>
Task<T> Promise<T>
namespace 不用 → 改用 import/export
HttpClient fetchaxios

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


相关推荐
wumingqilin2 小时前
QT 防抖和 节流处理
开发语言·qt
Mem0rin2 小时前
[Java/数据结构]顺序表之ArrayList
java·开发语言·数据结构
9稳2 小时前
基于PLC的生产线自动升降机设计
开发语言·网络·数据库·嵌入式硬件·plc
我是唐青枫2 小时前
C#.NET ReaderWriterLockSlim 深入解析:读写锁原理、升级锁与使用边界
开发语言·c#·.net
4ever.ov02 小时前
定时器/时间轮
开发语言·c++·c·muduo·llinux
编程之升级打怪2 小时前
用排他锁来实现Python语言的变量值更新
开发语言·python
rrrjqy2 小时前
Java基础篇(二)
java·开发语言
我命由我123452 小时前
React - React 配置代理、搜索案例(Fetch + PubSub)、React 路由基本使用、NavLink
开发语言·前端·javascript·react.js·前端框架·html·ecmascript
沐知全栈开发2 小时前
R 循环:深度解析与高效运用
开发语言