Contents (8)
- [Typescript] Type Narrow & CFA
- 1. Type Narrow by natural JavaScript [If Statements]
- 1.1 Primitive & built-in Type Narrow (typeof operator)
- 1.2 Object Type Narrow (in operator)
- 1.3 Class Type Narrow (instanceof operator)
- 1.4 JavaScript's built-in type-guard functions
- 1.5 Narrowing union types with comparison operators.
- 2. Type Guards, Type Assertions
[Typescript] Type Narrow & CFA
For union types like "string" | "number", TypeScript narrows the type through CFA (Control Flow Analysis) and user-defined functions, and shows the result to the developer.
Control Flow means the order in which each statement, instruction, or function in a program is executed or called. Statements that express control flow decide whether to run or skip something based on a condition, which helps change the call order or the flow, and they're called control statements. Typical boolean-logic control statements include if, switch, and try. It's the same as analyzing plain JavaScript code.
User-defined functions are types or type functions that use keywords like "is", "assert", "infer", and "as", or type Generics. What makes them different from types determined through CFA is that TypeScript's keywords all disappear after compilation.
The key point is that with CFA, types are also controlled through JavaScript code, so it affects the runtime, whereas types from user-defined functions don't affect the runtime.
1. Type Narrow by natural JavaScript [If Statements]
The simplest ways to narrow a type are JavaScript if statements and JavaScript type operators. There are three main type operators: typeof, in, and instanceof. They're used to tell apart Primitive + built-in Types, Objects, and Classes, respectively. How you narrow the type depends on the kind of variable you want to tell apart.
1.1 Primitive & built-in Type Narrow (typeof operator)
Primitive values include string, number, boolean, symbol, and so on. For these types, you can use the typeof operator to find out the variable's type and narrow it with an if statement. Built-in JavaScript types like "object" also
declare const getUserAge: () => undefined | number;const age = getUserAge(); // undefined | number;if (typeof age === 'undefined') return; // If age is undefined, we return => from the next line on, it's removed from the union type.const koreanAge = age + 1; // number;1.2 Object Type Narrow (in operator)
When you have two Objects, to check whether they're the same, you need to check whether they have the same Property. To check this in JavaScript, you have to directly check whether the object has the corresponding Property Key. The operator for this is in.
// 1. Comparing keys of different objectsdeclare const getUserAge: () => {value: number} | {error: Error};const age = getUserAge(); // {value: number} | {error: Error};if ("error" in age) return; // "error" exists as a property, so exit.const koreanAge = age.value + 1; // {value: number}// 2. Comparing key & value types of different objects.declare const getUserAge: () => | {value: number} | {value: undefined} | {error: Error};const age = getUserAge(); // {value: number} | {value: undefined} | {error: Error};if ("error" in age) return; if (typeof age.value === 'undefined') return; // {value: number} | {value: undefined}const koreanAge = age.value + 1; // {value: number}1.3 Class Type Narrow (instanceof operator)
Classes can be extended through inheritance. The class that inherits becomes the SubClass, and the class it inherits from becomes the SuperClass. An object created from the SubClass is an instance of the SubClass, but it can also be an instance of the SuperClass. Since the instanceof operator checks whether the instance's prototype chain contains an object that's the same as the Class's prototype, comparing it against any SuperClass of the instance's constructor class gives true. And TypeScript analyzes instanceof and if to perform Type Narrow.
instanceof decision criteria helper code.ts
class User { age: number; constructor(age: number) { this.age = age; }}class MVPUser extends User { money: number; constructor(age: number, money: number) { super(age); this.money = money; }}const commonUser = new User(20);const richUser = new MVPUser(21, 1000);if (richUser instanceof User) { console.log("i am user") // printed}if (commonUser instanceof User) { console.log("i also user") // printed}if (commonUser instanceof MVPUser) { console.log("am i rich user?") // X}if (richUser instanceof MVPUser) { console.log("i am rich user") // printed}if (commonUser instanceof Object) { console.log("i also Object") // printed}if ('age' in richUser) { console.log("i also object2") // printed}declare const getNumberOrNumbers: () => number | number[];const value = getNumberOrNumbers(); // number | number[]if (value instanceof Array) { console.log(value .length); // number[]} else { console.log(value .toPrecision(0)) // number}1.4 JavaScript's built-in type-guard functions
The Array class and the isArray function are one example of built-in type-guard functions.
declare const getNumberOrNumbers: () => number | number[];const myNum = getNumberOrNumbers(); // number | number[] ;if (Array.isArray(myNum)) { console.log(myNum.length); // number[]} else { console.log(myNum.toPrecision(0)) // number}1.5 Narrowing union types with comparison operators.
The first example narrows a literal type with an if statement and a comparison operator, and the second example uses the literal value to narrow the type even among Objects that share the same key, name.
litral type narrow.ts
declare const getSomething: () => "English1" | "English2" | 3;const something = getSomething(); // number | number[] ;switch (something) { case "English1": console.log(something + "string"); // "English1" break; case "English2": console.log(something + "string2"); // "English2" break; default: console.log(something + 10); // 3}if (something === 3) { console.log("number", something) // 3} else { console.log("text", something + "string3") // "English1" | "English2"}Discriminated Unions.ts
type Circle = { name: "circle"; radius: number;}type Square = { name: "square"; width: number;}type Diagram = Circle | Squarefunction getArea(diagram:Diagram) { switch(diagram.name) { case "circle": return diagram.radius * diagram.radius * 3.14; // Circle case "square": return diagram.width * diagram.width; // Square default: return 0; }}2. Type Guards, Type Assertions
Everything we did in Section 1 was actually a type guard. A type guard narrows down the type of a variable that could be one of several types.
The type guard I'll explain below is a user-defined type guard. It uses the type predicate keyword "is".
A type assertion declares that something must be a certain type. To manage types solidly, your code should also check the variable and boldly throw an Error if it isn't the type you want. You can assert with the as or assert keywords. It's often used when you have no other choice, like when a ThirdParty library has no type definitions. Or, if the types get too complicated, I think just using as can also help cut development costs.
Type Guard (user-defined)
Actually, if you use instanceof, the type gets inferred through CFA on its own even if you don't write obj is LayoutError.
declare const getError: () => NetworkError | LayoutError;class NetworkError extends Error { retryCount: number;};class LayoutError extends Error { target: string;};function isLayoutError(obj: Error): obj is LayoutError { return obj instanceof LayoutError;}const error = getError(); // NetworkError | LayoutErrorif (isLayoutError(error)) { console.error(error.target,"Layout error here") //LayoutError} else { console.error("Retry count:", error.retryCount) //NetworkError}A Confusing Type Guard
The type guard should have been LayoutError, but it was written wrong and the type got switched. It runs without any TS Error.
declare const getError: () => NetworkError | LayoutError;class NetworkError extends Error { retryCount: number;};class LayoutError extends Error { target: string;};function isLayoutError(obj: Error): obj is NetworkError { return obj instanceof LayoutError;}const error = getError(); // NetworkError | LayoutErrorif (isLayoutError(error)) { console.error(error.target,"Layout error here") // NetworkErrorThe developer wrote obj is NetworkError, so the type inference result got switched and it became the NetworkError type.} else { console.error("Retry count:", error.retryCount) // LayoutError}Assertion Function (asserts)
If you use assert, then after that function runs, the type is always automatically inferred as the asserted type. That's why I added code that throws an Error outright if the JavaScript check fails. It works without it too, but then type safety isn't guaranteed, as shown above.
declare const getError: () => NetworkError | LayoutError;class NetworkError extends Error { retryCount: number;};class LayoutError extends Error { target: string;};function assertLayoutError(obj: Error): asserts obj is LayoutError { if (!(obj instanceof LayoutError)) throw new Error("You said it would definitely be a LayoutError!!")}const error = getError(); // NetworkError | LayoutErrorassertLayoutError(error); console.log(error.target) // LayoutError;Assertion (as)
// Example 1: a typical type assertion.interface fruite { name: string; price: number;}var apple = {} as fruite;// Example 2: MouseEvent is a Subclass of Event. It's a type assertion TypeScript accepts, so no error is shown.(DownCasting)function onClick (event: Event) { let mouseEvent = event as MouseEvent;}// Example 3: since it's neither downcasting nor upcasting, a plain conversion shows a TS Error message. You have to go through unknown to convert it.// Of course, it depends on your tsConfig settingsinterface Message { content : string;}function onReceive(msg: Message) { let messageReceived = event as unkown as string;}as const
as const keeps an Object's properties from being widened into non-literal key-value types. Simply put, it turns the Object into a literal version.
const data1 = { name: "carrot"};const data2 = { name: "carrot"} as const;type Common = typeof data1[keyof typeof data1]; // stringtype Litral = typeof data2[keyof typeof data2]; // "carrot"