3. Most* modern web frontend
work is done via compiling
standards that don't yet exist in
older browsers to cross-platform
JavaScript.
* citation needed
4.
5. TypeScript provides a compiler
that can handle standard
JavaScript, and prepare it for older
targets.
It also understands some of its
own syntax to add compile-time
checks.
6.
7.
8. Great solutions exist for using
TypeScript in React applications
among other destinations.
Why do I like it so much?
9. Reasons I like TypeScript:
The compiler is smarter
than me
10. // using strict null checking...
function fooify(thing: string) {
return thing.toUpperCase();
}
fooify(undefined);
// ^^^^^^^^^
// [ts] Argument of type 'undefined' is not assignable
// to parameter of type 'string'.
Can't pass an unde ned to a
string parameter.
11. const stringOrFalse = (returnString: boolean) =>
(returnString) ? "hi" : false;
const fooify = (thing: string) => thing.toUpperCase();
const value = stringOrFalse(true);
fooify(value);
// ^^^^^
// [ts] Argument of type 'false | "hi"' is not
// assignable to parameter of type 'string'.
// Type 'false' is not assignable to type 'string'.
Value could be false.
12. const stringOrFalse = (returnString: boolean) =>
(returnString) ? "hi" : false;
const fooify = (thing: string) => thing.toUpperCase();
const value = stringOrFalse(true);
if (value) {
// value can't be 'false', so no error
fooify(value);
}
Compiler is smart enough to nd
conditions that narrow a value.
13. type Eel = string | 7;
type SwallowType = 'African' | 'European';
enum FavouriteColour {
blue = '#0000ff',
yellow = '#ffff00',
}
interface IHovercraft {
contents: Eel[],
}
Most types are very exible.
14. interface IUser {
name: string,
isAdmin: boolean,
}
const addUser = (user: IUser) => true;
addUser({name: 'Jesse Doe', isAdmin: true});
Most types are picked up without
needing to annotate them.
15. addUser({name: 'Alex Nguyen'});
// ^^^^^^^^^^^^^^^^^^^^^
// [ts] Argument of type '{ name: string; }' is not
// assignable to parameter of type 'User'.
// Property 'isAdmin' is missing in type
// '{ name: string; }'.
Error messages tell you why the
type doesn't work here.
16. interface IFeatureFlagList { [k: string]: boolean };
const makeFlagTester = (flags: IFeatureFlagList) =>
(flag: keyof IFeatureFlagList) =>
flags[flag];
const testFlag = makeFlagTester({
hasBakedBeans: false,
// error due to value
invasiveTracking: 'always!',
// error due to key
true: false,
});
17. interface IFeatureFlagList { [k: string]: boolean };
const makeFlagTester = (flags: IFeatureFlagList) =>
(flag: keyof IFeatureFlagList) =>
flags[flag];
const testFlag = makeFlagTester({});
// error: true can never be a key of
// IFeatureFlagList
testFlag(true);
// error: boolean doesn't have `toUpperCase`
testFlag('gamification').toUpperCase();