As perguntas da entrevista TypeScript em 2026 testam sua compreensão do sistema de tipos, genéricos, padrões avançados e integração com React e Node.js. Este guia cobre as perguntas mais comuns sobre TypeScript nos níveis júnior e sênior.
Perguntas principais do TypeScript
1. Qual é a diferença entre interface e alias de tipo?
// Interface — can be merged (declaration merging), preferred for objects
interface User {
id: number;
name: string;
}
// Extend interface
interface AdminUser extends User {
role: 'admin';
}
// Declaration merging (unique to interface)
interface User {
email: string; // adds to existing interface
}
// Type alias — more flexible, supports unions and intersections
type ID = string | number;
type Status = 'pending' | 'active' | 'inactive';
type ApiResponse<T> = { data: T; error: string | null; };
// Intersection
type AuthUser = User & { token: string };
// When to use:
// interface: for objects, especially when extending or merging
// type: for unions, intersections, primitives, tuples
2. Explique os genéricos com um exemplo real
// Generic function — works with any type
function first<T>(items: T[]): T | undefined {
return items[0];
}
const num = first([1, 2, 3]); // type: number | undefined
const str = first(['a', 'b']); // type: string | undefined
// Generic with constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: 'Alice', age: 30 };
const name = getProperty(user, 'name'); // type: string
// getProperty(user, 'foo'); // Error! 'foo' not in keyof User
// Generic class
class Repository<T extends { id: number }> {
private items: T[] = [];
add(item: T): void { this.items.push(item); }
findById(id: number): T | undefined {
return this.items.find(i => i.id === id);
}
getAll(): T[] { return [...this.items]; }
}
const userRepo = new Repository<User>();
userRepo.add({ id: 1, name: 'Alice' });
3. Quais são os tipos de utilitários? Dê exemplos
interface User {
id: number;
name: string;
email: string;
password: string;
role: 'admin' | 'user';
}
// Partial — all optional
type UserUpdate = Partial<User>;
// Required — all required (reverse of Partial)
type StrictUser = Required<User>;
// Pick — select fields
type PublicUser = Pick<User, 'id' | 'name' | 'email'>;
// Omit — exclude fields
type CreateUserInput = Omit<User, 'id'>;
type SafeUser = Omit<User, 'password'>;
// Readonly
type ImmutableUser = Readonly<User>;
// Record — map type
type UsersByRole = Record<'admin' | 'user', User[]>;
// Extract / Exclude
type StringOrNumber = string | number | boolean;
type OnlyString = Extract<StringOrNumber, string>; // string
type NoBoolean = Exclude<StringOrNumber, boolean>; // string | number
// ReturnType / Parameters
async function fetchUser(id: number): Promise<User> { /* ... */ return {} as User; }
type FetchResult = Awaited<ReturnType<typeof fetchUser>>; // User
type FetchArgs = Parameters<typeof fetchUser>; // [number]
// NonNullable
type MaybeUser = User | null | undefined;
type DefiniteUser = NonNullable<MaybeUser>; // User
4. Explique o tipo `unknown` versus `any`
// any — disables type checking (avoid!)
let a: any = 'hello';
a.toUpperCase(); // OK (even if string)
a.nonExistent(); // No error! Dangerous!
// unknown — type-safe alternative to any
let b: unknown = 'hello';
// b.toUpperCase(); // Error! Must narrow first
// b.nonExistent(); // Error!
// Must narrow unknown before use
if (typeof b === 'string') {
b.toUpperCase(); // OK — narrowed to string
}
// Real use case: typed error handling
async function fetchData(): Promise<unknown> {
const r = await fetch('/api/data');
return r.json();
}
const data = await fetchData();
if (typeof data === 'object' && data !== null && 'users' in data) {
console.log((data as { users: User[] }).users);
}
5. O que são tipos mapeados?
// Map over keys of an existing type
type Optional<T> = {
[K in keyof T]?: T[K];
};
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};
// Conditional mapped type — change type based on condition
type NonNullableProps<T> = {
[K in keyof T]-?: NonNullable<T[K]>; // -? removes optional
};
// Key remapping (TS 4.1+)
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<User>;
// { getId: () => number; getName: () => string; ... }
6. Tipos literais de modelo
type EventName = 'click' | 'focus' | 'blur';
type Handler = `on${Capitalize<EventName>}`;
// 'onClick' | 'onFocus' | 'onBlur'
type Route = '/users' | '/posts' | '/comments';
type ApiRoute = `${Route}/${number}`;
// '/users/1' | '/posts/2' etc.
// Real use case: CSS properties
type Side = 'top' | 'bottom' | 'left' | 'right';
type CSSPadding = `padding-${Side}`;
// 'padding-top' | 'padding-bottom' | 'padding-left' | 'padding-right'
// Event emitter with type safety
type Events = {
'user:created': { user: User };
'order:placed': { orderId: string; total: number };
};
declare function emit<K extends keyof Events>(event: K, data: Events[K]): void;
emit('user:created', { user: { id: 1, name: 'Alice' } }); // type-safe!
7. Sindicatos discriminados
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
function handleResult<T>(result: Result<T>) {
if (result.success) {
console.log(result.data); // TypeScript knows: data exists
} else {
console.error(result.error); // TypeScript knows: error exists
}
}
// Shape discriminated union
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rectangle'; width: number; height: number }
| { kind: 'triangle'; base: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'rectangle': return shape.width * shape.height;
case 'triangle': return 0.5 * shape.base * shape.height;
}
}
Sucesso na entrevista TypeScript: entenda profundamente o sistema de tipos (não apenas a sintaxe), explique por que os genéricos permitem a reutilização de código, saiba de cor os tipos de utilitários comuns e demonstre tipos condicionais + mapeados para questões avançadas. As entrevistas TypeScript testam cada vez mais a integração React + TypeScript – pratique ganchos de digitação, adereços e manipuladores de eventos.
🔗 Share this article
✍️ Leave a Comment