strictFunctionTypes
- TypeScript course
- Beginner
- Lesson 69/89
- 4 min
Learn strict function types.
What is strictFunctionTypes?
strictFunctionTypes checks the assignability of function parameter types using contravariant rules. This catches runtime errors in callback and handler assignments at compile time.
type Log = (msg: string) => void;
const log: Log = (msg) => console.log(msg);
log("merhaba");The contravariance rule
You can assign a (a: Animal) => void function where a (d: Dog) => void is expected; because a function accepting Animal also accepts Dog. The reverse assignment is an error with strictFunctionTypes on; a function expecting Dog may not accept Animal.
type Animal = { name: string };
type Dog = Animal & { age: number };
type AnimalFn = (a: Animal) => void;
type DogFn = (d: Dog) => void;
let af: AnimalFn = (a) => console.log(a.name);
let df: DogFn = af; // validPractice Safe assignment with function types
Define Animal as { name: string }. Define Dog as Animal & { age: number }. Define AnimalFn = (a: Animal) => void and DogFn = (d: Dog) => void. Define af as an AnimalFn (logging a.name), assign df: DogFn = af, and call df with { name: "Rex", age: 3 }.
Starter code
// Animal türünü tanımla: name alanı string
// Dog türünü Animal'ı genişleterek tanımla (age: number ekle)
// AnimalFn ve DogFn fonksiyon türlerini tanımla
// af'i AnimalFn olarak tanımla, a.name yazdırsın
// df: DogFn = af ata ve df'i Dog ile çağırSample solution
type Animal = { name: string };
type Dog = Animal & { age: number };
type AnimalFn = (a: Animal) => void;
type DogFn = (d: Dog) => void;
const af: AnimalFn = (a) => console.log(a.name);
const df: DogFn = af;
df({ name: "Rex", age: 3 });Expected output
Rex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 For which aspect does strictFunctionTypes bring stricter checking?
- Only for array elements
- For function parameter types Correct answer
- Only for object properties
- Only for return types
Explanation: strictFunctionTypes makes function parameter types be checked contravariantly. Return types are already covariant.
2 Complete the function type
type Log = (msg: ____) => void;
type Log = (msg: string) => void;
Explanation: A Log function takes a string message. any breaks type safety; number and boolean are the wrong type.
3 strictFunctionTypes parts
| Term | Meaning |
|---|---|
strictFunctionTypes |
Checks parameters contravariantly |
(a: Animal) => void |
A function type taking Animal |
Dog = Animal & { age: number } |
A subtype of Animal |
let df: DogFn = af |
Safe assignment direction |