C#教程

关注公众号 jb51net

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

C#转TypeScript的完整指南

作者:向上的车轮

本文对比了C#和TypeScript的异同,指出它们在变量类型、类与接口、泛型、异步编程等方面具有相似之处,同时也指出了TypeScript在运行环境、类型系统、基础类型、空值处理等方面的差异,并给出了从C#转向TypeScript的建议,强调C#经验可以直接迁移,需要的朋友可以参考下

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

特性说明
静态类型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 步上手)

写法习惯调整

善用 TS 的“超能力”

记住:TS ≠ 新语言,而是“带类型的 JS”

一句话总结:

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
HttpClientfetchaxios

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

以上就是C#转TypeScript的完整指南的详细内容,更多关于C#转TypeScript的资料请关注脚本之家其它相关文章!

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