Combining primitives and objects
Example: a primitive + an object in one union
javascript
type User = { name: string; age: number };
let value: string | User;
value = "Anonymous"; // a string - fits
value = { name: "Tim", age: 25 }; // an object - also fits
value = 42; // Error - a number is not part of the unionHere
valuecan be either a string or an object withnameandagefields.
Example: a function with a union of primitives and objects
javascript
type User = { id: number; name: string };
function printUser(user: string | User) {
if (typeof user === "string") {
console.log(`Username: ${user}`);
} else {
console.log(`ID: ${user.id}, Name: ${user.name}`);
}
}
printUser("Tim"); // a string
printUser({ id: 1, name: "Tim" }); // an objectWe use type narrowing (
typeof user === "string") to narrow the type and safely access the needed properties.
Example: combining several data shapes
javascript
type Product = { name: string; price: number };
type ProductInput = string | number | Product;
function handleProduct(p: ProductInput) {
if (typeof p === "string") {
console.log("Product by name:", p);
} else if (typeof p === "number") {
console.log("Product by ID:", p);
} else {
console.log("Product as an object:", p.name, p.price);
}
}Here
pcan be a string, a number, or an object - TypeScript guarantees that you check the type before using it.
Example: an object + null or undefined
A very common case: an object may be absent:
javascript
type User = { id: number; name: string } | null;
let currentUser: User = null; // OK
currentUser = { id: 1, name: "Tim" }; // OKThis lets you explicitly control the "no data" state.
Important to understand
When you combine primitives and objects, TypeScript:
- requires a type check before accessing properties;
- allows using shared properties, if all the variants have them.
Example:
javascript
type A = { id: number };
type B = string;
function show(a: A | B) {
// console.log(a.id); // not allowed - string has no id
if (typeof a !== "string") {
console.log(a.id); // safe
}
}Summary
| Can they be combined? | Yes |
|---|---|
| Primitives + objects | Yes |
| Any number of types | No limit |
| A check before use | Required |
| Used for | Universal functions, API responses, flexible structures |
In short:
Union types in TypeScript can be mixed freely -
string | number | { name: string } | nullis completely valid.The main thing is: check the type before accessing its properties.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.