Skip to content
typescriptbeginner

TypeScript Basics Quiz

Basic types, interfaces, type annotations, and TypeScript fundamentals.

7 questions

By EZ4Code Team

1. Which syntax correctly annotates a variable as a string?

let name: string = "Alice"
let name as string = "Alice"
let string name = "Alice"
let name = "Alice" :: string
Explanation: TypeScript uses `: type` annotation after the variable name. So `let name: string = "Alice"`. The `as string` syntax is for type assertions, and `::` is Haskell/Elm syntax.

2. What is the difference between `interface` and `type`?

They are completely different
Both define object shapes; `interface` is extendable via declaration merging
`type` is faster at runtime
`interface` only works with classes
Explanation: Both can describe object shapes. `interface` supports declaration merging (you can declare the same interface multiple times and they combine) and is preferred for extensible object contracts. `type` is more flexible — it can express unions, intersections, tuples, and primitives.

3. What does the `?` mean in this interface?

interface User {
  id: number;
  email?: string;
}
email is required
email is optional (may be undefined)
email must be a question
email is a string or null
Explanation: The `?` marks the property as optional. So `email` can be `string` or `undefined`. Note: this is different from `email: string | null` — `?` means the property may not exist at all, while `| null` means it must exist but can be null.

4. Which type represents "any value, but you should avoid using it"?

unknown
any
object
void
Explanation: `any` opts out of type checking entirely — you can do anything with it, which defeats TypeScript's purpose. Prefer `unknown` when you don't know the type: it forces you to narrow the type before using it.

5. What is the type of `x`?

let x = 42;
any
number
number | undefined
unknown
Explanation: TypeScript infers `x` as `number` from the literal `42`. You don't always need explicit annotations — inference works for most cases. The inferred type is `number`, not `42` (literal types only apply to `const`).

6. What does `as` do in TypeScript?

const el = document.getElementById("app") as HTMLDivElement;
Creates a new element
Performs a type assertion (tells the compiler the type)
Casts at runtime
Imports a module
Explanation: `as` is a type assertion — it tells the compiler "trust me, this is the type I say it is". It does NOT perform any runtime conversion. `getElementById` returns `HTMLElement | null`, and we assert it's specifically an `HTMLDivElement`.

7. Which is a valid union type?

let x: string | number
let x: string or number
let x: string + number
let x: Union<string, number>
Explanation: TypeScript uses `|` for union types: `string | number` means the value can be either a string or a number. `or`, `+`, and `Union<...>` are not valid syntax.

More typescript Quizzes