Typescript: best type checking for the best type safety

typescript:-best-type-checking-for-the-best-type-safety

C# and Typescript

Before using Typescript, I used C# for many years. Put aside the ecosystem and just from the language point of view, I still think C# is the best language I have ever used, which is mainly because of the robust and powerful type system. It is really a pleasure to write code with good type inference, even for the generics, and very few annoying runtime errors.

Therefore, the moment I heard about Typescript, I knew I would definitely use it seriously for sure.

Why? because of the Hejlsberg

breaking bad

No, not either of the guy above, although the name looks similar. 😆 It is this guy:

Hejlsberg

If you have ever dived into the source code of Typescript, you should be familiar with him as he made the most commits in the repository and is also the original designer of C#, Delphi, and Turbo Pascal.

Hejlsberg-commit

Therefore, I knew Typescript would definitely inherit the good quality from C#. What I was not aware of is that It is more than that.

Exceed

I’m building a new toolkit ZenStack to help people build secured full-stack web apps easily. It has its own DSL(Domain specified Language) ZModel, which I chose the OSS library Langium to implement. It does a good job of parsing the language text to AST (abstract syntax tree), but it doesn’t support generating code back from AST reversibly. Therefore I have to do that by myself. Luckily, I have done this using C# before. So to some degree, it’s like translating C# to Typescript for me. 😏

When handling the binary expression, it needs to consider the operator precedence to see whether to generate a parenthesis. So following the old road, the first thing is to define the precedence for all the operators. In C#, it can be done by using a dictionary, in Typescript, we can simply use a const object:

export const BinaryExprOperatorPrecedence  = {
    //LogicalExpr
    '||': 1,
    '&&': 1,
    //EqualityExpr
    '==': 2,
    '!=': 2,
    //ComparisonExpr
    '>': 3,
    '<': 3,
    '>=': 3,
    '<=': 3,
    //TODO: add more operators
};

To make it run e2e first, I only added the most obvious operators and left a TODO there as usual.

Then when handling the binary expression, I need to get the precedence first. The code I was about to write is as below:

code-error-1

An interesting thing happened. As you can see, there was a type error for getting the current precedence from the BinaryExprOperatorPrecedence. How come?

After checking the error message, you will know why:

Element implicitly has an 'any' type because expression of 
type '"!" | "!=" | "&&" | "<" | "<=" | "==" | ">" | ">=" | "?" | 
"^" | "||"' 
can't be used to index type '{ '||': number; '&&': number; 
'==': number; '!=': number; '>': number; '<': number; 
'>=': number; '<=': number; }'.

Property '!' does not exist on type '{ '||': number; '&&': number; 
'==': number; '!=': number; '>': number; '<': number; 
'>=': number; '<=': number; }'.ts(7053)

It turns out that it doesn’t give you the chance to throw the NotImplemented exception at all, you have to define all the operators to pass the type checking. 😂

It might sound like extra work, but think about what will happen if later there is a new kind of operator added by someone unaware of my code. He will immediately see the type-checking error above and know he needs to also add the precedence for that operator here. Isn’t this exactly the benefit of type-checking:

Fail fast, Fail often

How to get that

Simply by checking the type definition of the operator, you will see how simple and intuitive to use a union to represent it:

operator: '!' | '!=' | '&&' | '<' | '<=' | '==' | '>' | '>=' 
| '?' | '^' | '||';

Union type is such a great feature to make a stronger type system because it allows you to build new types out of existing ones using a large variety of operators. I think that’s one reason to make Typescript shines because very few mainstream programming languages have built-in support for union. So far as I know, only Scala and Rust also support it.

Beyond

One experience I would like to share when starting to use Typescript is always to ask: can we fail faster?

Yes, we can! Simply just giving the explicit type for BinaryExprOperatorPrecedence as Record

code-error-2

Then rather than see an error where the BinaryExprOperatorPrecedence is used, you will see an error right away with the below message:

Type '{ '||': number; '&&': number; '==': number; '!=': number; 
'>': number; '<': number; '>=': number; '<=': number; }' 

is missing the following properties from type 

'Record<"!" | "!=" | "&&" | "<" | "<=" | "==" | ">" | ">=" | "?" 

| "^" | "||", number>': "!", "?", "^"ts(2739)

BTW, if you used C# like me before, you might want to define the operator as an Enum. You can still do that here without losing any benefits like the below:

enum Operator {
  Add = "+",
  Subtract = "-",
  Multiply = "*",
  Divide = "/",
}

export const BinaryExprOperatorPrecedence:Record<Operator, number> 
= {...}

Although I don’t see a strong point in doing that since Union has done a great job already.

Attention!

There is an essential prerequisite for all the benefits mentioned, and I think it should be a motto for all the typescript users:

If you want to feel safe, work in the Strict mode

Total
0
Shares
Leave a Reply

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

Previous Post
enhance-your-product-marketing-approach-with-the-product-marketing-core:-two-day-in-person-workshop-|-berlin-|-may-3-–-4,-2023

Enhance your product marketing approach with the Product Marketing Core: Two-day in-person workshop | Berlin | May 3 – 4, 2023

Next Post
insurance-industry-in-canada:-top-trends-and-challenges-in-2023

Insurance Industry In Canada: Top Trends and Challenges in 2023

Related Posts

状态模式深度指南:构建可动态切换行为的艺术

状态模式深度指南:构建可动态切换行为的艺术 概述 状态模式(State Pattern)是一种行为型设计模式,它允许对象在内部状态改变时改变其行为。看起来对象似乎修改了其类。这种模式是解决复杂状态转换逻辑的利器,特别适合用于工作流引擎、游戏开发、订单处理系统等场景。 核心概念 状态模式的核心思想是:将每个状态封装为独立的类,对象的行为取决于其当前状态,而状态之间的转换由状态类自己管理。 关键角色 Context(上下文):维护当前状态的实例,负责将请求委托给状态对象处理 State(抽象状态):定义所有具体状态的共同接口 ConcreteState(具体状态):实现各个具体状态的行为,并负责状态转换 为什么需要状态模式? 传统方式的困境 想象一个订单系统,订单有多种状态:待支付、待发货、已发货、已完成、已取消。每个状态下可以执行不同的操作。 // 传统的if-else方式 class Order {…
Read More