My Typescript to C# Cheatsheet

As a software consultant, my job involves working with the most suitable programming language for each project. Until recently, this has consistently been TypeScript. However, on my current project, I have the opportunity to learn a language that is new to me: C#. To facilitate this learning process, I created a cheat sheet to help map commonly-used TypeScript concepts to their C# counterparts. It turns out, the two languages are more similar than I anticipated!

These mappings have been incredibly helpful for me, so for anyone who is in the same boat, I give you my definitive TS -> C# cheatsheet! I hope you enjoy 😃.

Mapping TS array methods to C# Linq equivalents

✅ C# supports arrow functions
The System.Linq namespace in C# contains methods equivalent to Typescripts’s functional array methods. The following table maps TS methods to their C# Linq equivalents with examples for each.

Given:
Example TS array:

const strings = ['one', 'two', 'three', 'four'];

Example C# list:

var strings = new List<string> { "one", "two", "three", "four" };
Typescript method Equivalent in C# Use
Array.prototype.filter

// Will return [“three”, “four”]

const result = strings.filter((str) => str.length > 3);
Enumerable.Where()

// Will return {“three”, “four”}

var result = strings.Where(str => str.Length > 3);
Returns an array containing the elements from the given array which satisfy the provided condition.
Array.prototype.map()

// Will return [3, 3, 5, 4]

const result = strings.map((str) => str.length);
Enumerable.Select()

// Will return { 3, 3, 5, 4 }

var result = strings.Select(str => str.Length);
Returns array containing the results of invoking the provided function on every element in the given array.
Array.prototype.reduce()

// Will return 15

const initialValue = 0;
const result = strings.reduce((accumulator, currentValue) => accumulator + currentValue.length, initialValue,);
Enumerable.Aggregate()

// Will return 15

var initialValue = 0;
var result = strings.Aggregate(initialValue, (accumulator, currentValue) => accumulator + currentValue.Length );
Returns a single value which is the result of running the provided accumulator function on each element of the given array, in order, passing the return value from the calculation on the preceding element to the next iteration.
Array.prototype.find()

// Will return “three”

const result = strings.find((str) => str.length > 3);
List.Find()

// Will return “three”

var result = strings.Find(str => str.Length > 3);
Returns the first value from the provided array that satisfies the given condition.
Array.prototype.findIndex()

// Will return 2

const result = strings.findIndex((str) => str.length > 3);
List.FindIndex()

// Will return 2

var result = strings.FindIndex(str => str.Length > 3);
Returns the index of the first value from the provided array that satisfies the given condition.
Array.prototype.every()

// Will return true

const result = strings.every((str) => str.length > 2);
Enumerable.All()

// Will return True

var result = strings.All(str => str.Length > 2);
Returns a boolean indicating whether all elements of the given array satisfy the provided condition.
Array.prototype.some()

// Will return true

const result = strings.some((str) => str === ‘four’);
Enumerable.Any()

// Will return True

var result = strings.Any(str => str == “four”);
Returns a boolean indicating whether any elements of the given array satisfy the provided condition.
Array.prototype.flatMap()

// Will return ["o", "n", "e", "t", "w", "o", "t", "h", "r", "e", "e", "f", "o", "u", "r"] 

const result = strings.flatMap((str) => str.split(‘’));
Enumerable.SelectMany()

// Will return [“o”, “n”, “e”, “t”, “w”, “o”, “t”, “h”, “r”, “e”, “e”, “f”, “o”, “u”, “r”] 

var result = strings.SelectMany(str => str.ToCharArray());
Returns an array formed by invoking the provided function on every element in the given array and flattening the result by one level.

 

Mapping JS Promise APIs to C# Task API equivalents

✅ C# supports async/await
HOWEVER, C# uses the word “Task” in place of “Promise.” These concepts are identical in theory and have matching methods. The following table maps TS methods to their C# equivalents.

JavaScript API Equivalent C# API Use
Promise.prototype.then() Task.ContinueWith() Allows chaining of promises/tasks
new Promise() new TaskCompletionSource() Creates a promise/task object
Promise.resolve() Task.FromResult() Creates a promise/task that is completed with the specified result
Promise.reject() Task.FromException() Creates a promise/task that is rejected with the given reason
Promise.all() Task.WhenAll() Creates a promise/task that will complete when all of the specified tasks have completed
Promise.race() Task.WhenAny() Creates a promise/task that will complete when any of the supplied tasks have completed

 

Null & optional values in C# and Typescript

✅ C# and TS Share operators for handling null/optional values

Feature name Syntax Use
Optional properties property? Indicates a property is optional
Non-null assertion object!.property Asserts its operand is not null, supresses nullable warnings
Optional chaining object?.property Allows operation only if operand is not null; otherwise, short circuits and returns null
Nullish coalescing object ?? alternativeValue Returns the right-hand side operand when the left-hand side operand is null

Additional Notes

✅ C# supports try/catch/finally
In addition, it allows catching and handling specific types (instead of using a single catch() and checking the error type within)

✅ In C#, it is safe to combine ForEach with async expressions 🎉

✅ C# supports dynamic types, e.g. var x = {}
– Dynamic is a static type, but it bypasses static type checking
– If the code isn’t valid, errors surface at runtime

✅ Like JS, functions are first-class objects in C#
– You can pass, return and invoke function references like in JS/TS

Sources / Further Reading:

Microsoft’s Roadmap for JavaScript and TypeScript developers learning C#
Why C# goes well with TypeScript

Conversation
  • Solar says:

    Great job! This article was very well-explained.

  • noro5 says:

    There is no coincidence that they are similar – author of C#, Anders Hejlsberg, worked on TypeScript :D

  • Join the conversation

    Your email address will not be published. Required fields are marked *