26
loading...
This website collects cookies to deliver better user experience
noImplicitAny
strictNullChecks
noImplicitAny
is enabled all variables must have a known type.function greet(name) {
return `Hello, ${name}`
}
name
is of type any
.name
is implicitly of type any
, and if noImplicitAny
is disabled TypeScript will rightfully complain 🙂any
bypasses TypeScript's type checks, making values of the any
type assignable to anything.any
type should generally be your last resort and if you really need to use it, you have to do so explicitly if noImplicitAny
is enabled.noImplicitAny
enables you to make the most out of TypeScript, it can be tough to have this setting enabled if you are migrating your codebase from JavaScript, for example.strictNullChecks
controls if null
and undefined
are part of every type.const jame: Person = null
// It'll throw "cannot read 'greet' of undefined" at runtime
jame.greet()
strictNullChecks
enabled, TypeScript will tell you at compile time instead:Type 'null' is not assignable to type 'Person'.
strict: true
. any
, which is often perceived as the universal set.any
for, then?any
enables that, disabling the type checks. any
type to anythingany
typeany
doesn't fit in the "type as a set of values" model, since a set cannot be a subset and a superset of everything at the same time.// No errors even with strict: true
const age: number = "4" as any
const name: any = 3.1416
any
as a return type as it can spread to other well typed parts of your code that make use of said function.unknown
:unknown
because every type is a subset of it.unknown
is not assignable to any type but itself (or any
) because it is not the subset of any other type.unknown
is an error. any
for edge cases when we really don't know the return type of a function, for example.unknown
, the untyped code doesn't spread as we need to narrow the types in it in order to use it.function query<T>(q: string): T;
const result = db.query<User[]>('select * from user')
never
type is the opposite of unknown
:never
because no set is a subset of the empty set.never
is assignable to everything, because the empty set is the subset of every set.never
is not as frequent as unknown
but it does have an use case that I like a lot called exhaustive type checking:type SpanishChampionsWinners = 'Real Madrid' | 'Barcelona'
function getChampionsCount(team: SpanishChampionsWinners): number {
switch (team) {
case 'Real Madrid':
return 13;
case 'Barcelona':
return 5;
default:
const exhaustiveCheck: never = team;
throw new Error(`We forgot: ${team}`);
}
}
SpanishChampionsWinners
type will make this code complain since no value is assignable to never
.noImplicitAny
and strictNullChecks
well.any
does not fit in the "types as sets" model, being a mechanism to avoid types in parts of your code.any
spreading.unknown
is preferable to any
when handling edge cases.never
and use it for exhaustive checking.