TypeScript Types:  Any, Object, Unknown and Never

TypeScript Types: Any, Object, Unknown and Never

TypeScript is a superset of JavaScript that adds static types to the language. Types help us to write more robust and maintainable code, as well as tackle errors at compile time. TypeScript has many built-in types, such as number, string, boolean, array, ...etc. But it also has some special types that are useful for different scenarios. In this article, we will explore four of these special types: any, object, unknown and never. We will see what they mean, how they differ, and when to use them.

Any: The Flexible Type

The any type in TypeScript allows us to use a variable as if it could be any data type. We can assign any value to a variable of type any, and we can perform any operation on it without any type checking or error. For example:

let x: any = "hello";
x = 42; // OK, x is now a number
x = true; // OK, x is now a boolean
x.foo(); // OK, no error even if x has no foo method
        

The any type is useful when we don’t know or care about the type of a variable, such as when we get data from user input or external sources. However, using any too much can defeat the purpose of TypeScript, as we lose the benefits of type checking and code completion. It is usually a temporary solution or a last resort when we have no other type information available.

Object: The General Type

The object type in TypeScript represents any non-primitive value, such as an array, a function, a class, or an object literal. We can assign any object-like value to a variable of type object, but we cannot perform any operation on it that is not common to all objects. For example:

let y: object = { name: "Alice", age: 30 };
y = [1, 2, 3]; // OK, y is now an array
y = () => console.log("hello"); // OK, y is now a function
y.name; // Error, property 'name' does not exist on type 'object'
y.length; // Error, property 'length' does not exist on type 'object'
y(); // Error, y is not callable
        

The object type is useful when we want to restrict a variable to only hold non-primitive values, such as when we use the Object.keys or Object.values methods. However, using object is not very precise, as we lose the specific properties and methods of the actual object type. It is usually better to use a more specific type, such as an interface or a class, to describe the shape of an object.

Unknown: The Safe Type

The unknown type in TypeScript is similar to the any type, as it can hold any value. However, the unknown type is more restrictive than the any type, as it does not allow us to perform any operation on it without first checking its type. For example:

let z: unknown = "hello";
z = 42; // OK, z is now a number
z = true; // OK, z is now a boolean
z.foo(); // Error, Object is of type 'unknown'
z + 1; // Error, Object is of type 'unknown'
if (typeof z === "string") {
  z.toUpperCase(); // OK, z is a string inside this block
}
        

The unknown type is useful when we want to represent a value that we don’t know yet, such as when we get data from an API or a library. It forces us to check the type of the value before using it, which makes our code more robust and safe. It is usually a better alternative to the any type, as it preserves the type information and prevents us from making mistakes.

Never: The Impossible Type

The never type in TypeScript represents a value that never occurs, such as the return type of a function that always throws an error or never returns. We cannot assign any value to a variable of type never, and we cannot perform any operation on it. For example:

function throwError(message: string): never {
  throw new Error(message);
}

function loopForever(): never {
  while (true) {}
}

let a: never = throwError("something went wrong"); // OK, a is never assigned
let b: never = loopForever(); // OK, b is never assigned
let c: never = 42; // Error, Type 'number' is not assignable to type 'never'
let d: never = a; // OK, d is also never
d.foo(); // Error, Object is of type 'never'
d + 1; // Error, Object is of type 'never'
        

The never type is useful when we want to express that something is impossible or unreachable in our code, such as a branch of a switch statement that should never be executed. It helps us to catch errors and bugs at compile time, and to make our code more expressive and accurate.

Conclusion

In this article, we have learned about four special types in TypeScript: any, object, unknown and never. We have seen what they mean, how they differ, and when to use them. Here is a summary of the main points:

  • any is the most flexible type, as it allows us to do anything with a variable without any type checking or error. However, it also defeats the purpose of TypeScript, as we lose the benefits of type checking and code completion. Use any only when necessary, and avoid it when possible.
  • object is the most general type, as it represents any non-primitive value. However, it is also not very precise, as we lose the specific properties and methods of the actual object type. Use object only when you need to restrict a variable to non-primitive values, and prefer a more specific type when possible.
  • unknown is the most safe type, as it represents a value that we don’t know yet. It forces us to check the type of the value before using it, which makes our code more robust and safe. Use unknown as a better alternative to any, and narrow it down to a more specific type when possible.
  • never is the most impossible type, as it represents a value that never occurs. It helps us to express that something is impossible or unreachable in our code, and to catch errors and bugs at compile time. Use never to indicate that a function never returns or a branch never executes, and avoid assigning any value to it.

I hope this article helped you to understand the TypeScript any, object, unknown and never types better. If you have any questions or feedback, please leave a comment below. Thank you for reading!

要查看或添加评论,请登录

Hassan Fathy的更多文章

  • TypeScript - Types vs. Interfaces

    TypeScript - Types vs. Interfaces

    As TypeScript continues to gain popularity among developers for adding type safety to JavaScript, one of the frequent…

  • React - CSS Modules

    React - CSS Modules

    Introduction: In the bustling world of React development, there's a constant quest for more maintainable and scalable…

  • React - Redux Toolkit with TypeScript

    React - Redux Toolkit with TypeScript

    Introduction As a developer, you’ve probably heard about Redux and its powerful state management capabilities. However,…

  • Typescript - Truthiness

    Typescript - Truthiness

    What is truthiness? Truthiness is a term coined by comedian Stephen Colbert to describe something that feels true, even…

  • React - React Router v6

    React - React Router v6

    React Router is a popular library for declarative routing in React web applications. It allows you to define routes as…

  • TypeScript - Equality

    TypeScript - Equality

    TypeScript’s static type checking adds a layer of complexity and safety to equality comparisons, but the JavaScript…

  • React - Hooks(useRef)

    React - Hooks(useRef)

    React's useRef is a hook, a special function that taps into React features in functional components. It returns a…

    2 条评论
  • TypeScript - typeof vs instanceof

    TypeScript - typeof vs instanceof

    Introduction: Unwrap the mysteries of type assertions in TypeScript with two powerful operators: typeof and instanceof.…

  • React - Hooks(useReducer)

    React - Hooks(useReducer)

    Introduction: In the evolving landscape of React, managing state efficiently is critical for crafting responsive and…

  • TypeScript - Type Guards / Narrowing

    TypeScript - Type Guards / Narrowing

    Introduction: In the dynamic world of web development, TypeScript has emerged as an essential tool for building robust…

社区洞察

其他会员也浏览了