Type Assertions
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 68 of 73.
Sometimes TypeScript doesn't have enough information to determine the exact type of a value, but you as the developer know more about what that value actually is. Type assertions allow you to tell TypeScript "trust me, I know this value is of this specific type."
TypeScript provides two syntaxes for type assertions. The as syntax is the more common approach:
let data: unknown = '{"name": "John", "age": 30}';
let user = data as string;You can also use the angle-bracket syntax, though it's less common in modern TypeScript:
let data: unknown = '{"name": "John", "age": 30}';
let user = <string>data;This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a function that processes data from an external API simulation. You'll work with values of type unknown and use type assertions to safely access their properties.
Create a variable apiResponse of type unknown and assign it the following JSON string:
{"userId": 42, "username": "alice_dev", "isActive": true}Create a function named processUserData that:
- Takes a parameter
dataof typeunknown - Uses a type assertion to treat
dataas astring - Parses the JSON string using
JSON.parse() - Uses another type assertion to treat the parsed result as an object with properties
userId(number),username(string), andisActive(boolean) - Returns a formatted string:
"User [userId]: [username] (Active: [isActive])" - Has an explicit return type of
string
Create additional test data:
- Create
secondApiResponseof typeunknownwith the JSON string:{"userId": 15, "username": "bob_admin", "isActive": false} - Create
thirdApiResponseof typeunknownwith the JSON string:{"userId": 99, "username": "charlie_user", "isActive": true}
Test your function and print the following outputs:
- Call
processUserDatawithapiResponseand print the result - Call
processUserDatawithsecondApiResponseand print the result - Call
processUserDatawiththirdApiResponseand print the result
Cheat sheet
Type assertions allow you to tell TypeScript the specific type of a value when you know more than TypeScript can infer.
Use the as syntax (most common):
let data: unknown = '{"name": "John", "age": 30}';
let user = data as string;Alternative angle-bracket syntax:
let data: unknown = '{"name": "John", "age": 30}';
let user = <string>data;Try it yourself
// Create the API response variables
const apiResponse: unknown = '{"userId": 42, "username": "alice_dev", "isActive": true}';
const secondApiResponse: unknown = '{"userId": 15, "username": "bob_admin", "isActive": false}';
const thirdApiResponse: unknown = '{"userId": 99, "username": "charlie_user", "isActive": true}';
// TODO: Create the processUserData function here
// Test the function and print results
console.log(processUserData(apiResponse));
console.log(processUserData(secondApiResponse));
console.log(processUserData(thirdApiResponse));This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos8Enums
What is a Numeric Enum?Using Numeric EnumsWhat is a String Enum?Using String EnumsHeterogeneous EnumsRecap: Using Enums11Advanced Topics
Type Assertions Type Guards: in & instanceofThe 'never' TypeNullable Types ('strictNull')Index Signatures for ObjectsRecap: Fine-Tuning Types3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples