Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 96 ยท Functions

this, Parameter Destructuring and Type Predicates

Learn to type this in TypeScript functions, destructured parameters with defaults, type predicates (x is T), assertion functions and inferred type predicates.

This lesson finishes the Functions chapter with three features you'll use constantly in real code. Destructured parameters let a function take an options object and unpack it right in the signature. The this parameter tells TypeScript what this refers to inside a function, catching the classic "lost this" bug. And type predicates and assertion functions let your own functions teach the compiler something new: "if this returns true, the value is a string," or "if this returns at all, the value isn't null."

Type predicates are the bridge to the next chapter, Narrowing. They're how you turn an untyped value, such as parsed JSON, into a typed one safely, without the as assertions you were warned about in Type Assertions and the Non-Null Operator.

Destructured parameters

When a function takes several settings, an options object is easier to call than a long list of positional arguments. You can destructure it directly in the parameter list. The type annotation goes after the whole pattern:

TypeScript Destructuring an options object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Because the defaults fill in missing values, method, retries and timeoutMs have plain types inside the body, without | undefined. Call sites stay readable ({ url, method: 'POST' } names every value), and adding a new option later doesn't break existing calls. The = {} default on paginate lets callers omit the object entirely.

The renaming trap

Inside a destructuring pattern, a colon means rename, not "has type". This is a frequent mistake when people try to put types inline. This example fails on purpose:

TypeScript A colon inside the pattern renames (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The pattern { name: string, age: number } means "take name and call the variable string; take age and call it number." There's no type at all, so strict mode reports:

TEXT
main.ts(1,24): error TS7031: Binding element 'string' implicitly has an 'any' type.
main.ts(1,37): error TS7031: Binding element 'number' implicitly has an 'any' type.

The fix is to keep the pattern and the type separate: function greet({ name, age }: { name: string; age: number }). For anything longer than two properties, name the type with an interface, as FetchOptions does above. The JavaScript side of destructuring, including renaming on purpose, is covered in Destructuring.

Typing this

In JavaScript, this inside a regular function depends on how the function is called, not where it was written. Call it as obj.method() and this is obj; pull the method out into a variable and call it alone, and this is undefined in strict-mode code. (See this for the full rules.)

TypeScript lets you declare the expected this with a special first parameter named this. It's not a real parameter: callers don't pass it, and it's erased from the JavaScript output. It only tells the checker what this must be:

TypeScript Declaring the type of this

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

deposit.call(other, 5) is checked as well: the first argument must be an Account and the rest must match the real parameters. That checking comes from strictBindCallApply, part of the strict family described in Strict Mode Explained.

Catching lost this

The real value of this types is catching calls where this would be wrong. Here a method is extracted from its object and called on its own. This example fails on purpose:

TypeScript Calling a method without its object (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The call on line 15 is rejected:

TEXT
main.ts(15,1): error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'Counter'.

Without the this: Counter annotation, this code would compile and then crash at runtime with "Cannot read properties of undefined". Inside increment() { ... } no annotation was needed: the method is contextually typed by the Counter interface, so this is already Counter there.

A few more rules round out this typing:

  • In a standalone function that uses this without an annotation, strict mode (noImplicitThis) reports TS2683, "'this' implicitly has type 'any' because it does not have a type annotation."
  • this: void declares that a function must not use this. Libraries use it for callbacks to make sure you don't pass a method that depends on its object.
  • Arrow functions don't have their own this; they use the this of the surrounding code. You can't give an arrow function a this parameter. That's why arrow functions are the usual fix for lost this in callbacks.
  • In classes, this inside methods is the instance type automatically. Classes covers class methods, and the polymorphic this return type used for fluent APIs.

Type predicates: functions that narrow

TypeScript narrows types inside if statements when it sees checks it understands, like typeof x === 'string'. But if you move that check into a helper function, the narrowing is lost by default, because a function returning boolean says nothing about its argument.

A type predicate fixes that. Write the return type as paramName is Type. When the function returns true, TypeScript narrows the argument to Type; when it returns false, it narrows to the rest:

TypeScript A user-defined type guard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The predicate also works with array methods: library.filter(isBook) has the type Book[], not Media[], because filter has an overload for type-guard callbacks. That's why book.pages needs no check in the reduce.

TypeScript trusts a type predicate; it doesn't check that the body actually proves it. A predicate like function isBook(item: Media): item is Book { return true; } compiles and makes TypeScript treat every movie as a book. Keep predicate bodies small and obviously correct, and test them. A lying predicate is as dangerous as a wrong as.

Inferred type predicates (TypeScript 5.5+)

Since TypeScript 5.5, you often don't need to write x is T yourself. When a function has no return type annotation, returns a boolean, and its body is a check TypeScript understands, the compiler infers the predicate:

TypeScript Predicates inferred from the function body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The last case shows the rule TypeScript uses: it only infers x is T when both outcomes are exact. If the function returns true, x must be T; if it returns false, x must not be T. !!n returns false for 0, which is a number, so "false means not a number" would be wrong, and no predicate is inferred. When you want a predicate that inference can't produce, write x is T explicitly, or make the check precise (n !== undefined).

Before 5.5, readings.filter((x) => x !== undefined) stayed (number | undefined)[], so older code is full of hand-written helpers like isDefined. You'll see those in existing codebases; in new code, inference usually handles it.

Assertion functions

A type predicate narrows inside an if. An assertion function narrows everything after the call: if it returns at all, the condition holds; if not, it throws. The return type is asserts param is Type, or asserts param for "is truthy":

TypeScript asserts value is T

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

After assert(typeof data === 'object' && data !== null, ...), TypeScript knows data is an object, and after the in checks it knows price and percent exist (as unknown). Each assertIsNumber call then narrows its variable to number for the rest of the function. That's a complete, safe validation of untyped JSON with no as anywhere. Custom Type Guards builds on this for whole objects, and Error Handling shows how to narrow the caught error without the assertion used in the catch block above.

Assertion functions have one technical requirement: TypeScript must know the function's type before analyzing the call, so every name in the call must have an explicit type. Function declarations, like the ones above, always qualify. An arrow function stored in a const without a type annotation doesn't, and calling it gives error TS2775, "Assertions require every name in the call target to be declared with an explicit type annotation." Use a function declaration, or annotate the constant with a function type.

Predicate or assertion?

Type predicate Assertion function
Return type value is T asserts value is T or asserts value
Returns true or false Nothing (void), or throws
Narrowing applies Inside if, filter, ternaries Everywhere after the call
Good for Branching, filtering arrays Validating input, invariants, "this can't happen" checks

Use a predicate when both outcomes are normal, like sorting items into books and movies. Use an assertion when the failing case is an error that should stop the function.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does function show({ title: string }) {} declare?

    Inside a destructuring pattern, a colon renames. Under strict mode this fails with TS7031. Write function show({ title }: { title: string }) instead.
  2. 2. Given function area(this: { w: number; h: number }) { return this.w * this.h; }, how many arguments does a caller pass in area.call(rect)?

    The this parameter is a type-only fake parameter and is erased. call passes rect as this, and area has no real parameters.
  3. 3. What is the type of [1, 0, undefined].filter((n) => n !== undefined) in TypeScript 5.5 and later?

    TypeScript infers the predicate n is number from the precise check, and filter's type-guard overload returns number[]. With a truthiness check like !!n no predicate would be inferred.
  4. 4. An arrow function is declared as const check = (v: unknown): asserts v is string => { ... }; and then called as check(x). What happens?

    Assertion calls require every name in the call target to have an explicit type. Annotate const check with a function type or use a function declaration.
  5. 5. Which statement about function isAdmin(u: User): u is Admin is true?

    Type predicates are trusted, not verified. A wrong body silently produces wrong types, so keep predicates simple and test them.

Summary

  • Destructure an options object right in the parameter list, with the type after the pattern: ({ url, retries = 3 }: Options). Defaults remove undefined from the types.
  • A colon inside a destructuring pattern renames; it doesn't add a type (TS7031 under strict).
  • A fake first parameter this: T types this. It's erased at runtime and catches "lost this" calls with TS2684; untyped this in a function is TS2683.
  • A type predicate (value is T) makes a boolean function narrow its argument in if statements and in filter. It's trusted, not verified.
  • TypeScript 5.5+ infers predicates for precise checks like x !== undefined, but not for truthiness checks.
  • An assertion function (asserts value is T, asserts condition) narrows everything after the call or throws. Call targets need explicit types (TS2775).

Next: Narrowing