Repl https://www.typescriptlang.org/play
over view https://github.com/ruizb/glossary-typescript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
https://www.youtube.com/watch?v=eJ6R1knfsoc&t=160s
if ('make' in car === false) {
car.make = 'Suzuki';
}
https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates
https://www.youtube.com/watch?v=eJ6R1knfsoc&t=237s
type Car = {
wheels: number
};
type Boat = {
isSaltWater: boolean
}
type Vehicle = Car | Boat;
// Type Predicate
const isCar = (v: Vehicle): v is Car => {
return 'wheels' in v;
};
(function (a: Vehicle)
{
if(isCar(a))
{
console.log(a.wheels);
}
})({isSaltWater: true});
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions
https://www.youtube.com/watch?v=eJ6R1knfsoc&t=580s
/*
The first type of assertion signature models the way that Node’s assert function works. It ensures that whatever condition is being checked must be true for the remainder of the containing scope.
*/
function assert(condition: any, msg?: string): asserts condition {
if (!condition) {
throw new AssertionError(msg);
}
}
// must be a string
function assertIsString(val: any): asserts val is string {
if (typeof val !== "string") {
throw new AssertionError("Not a string!");
}
}
// value cannot be null or undefined
function assertIsDefined<T>(val: T): asserts val is NonNullable<T> {
if (val === undefined || val === null) {
throw new AssertionError(
`Expected 'val' to be defined, but received ${val}`
);
}
}
https://www.youtube.com/watch?v=eJ6R1knfsoc&t=753s
type Person = {
name: string;
address: {
city: string;
state: string;
zip: number;
}
}
type Address = Person['address'];
const a: Address = { city: '', state: '', zip: 0 };
https://www.youtube.com/watch?v=eJ6R1knfsoc&t=845s
enum InputTypes {
email = 'email',
phone = 'phone'
}
type UserInput<T = InputTypes> = {
value: string;
type: T
}
const field1: UserInput = {
value: '',
type: InputTypes.email
};
field1.type = InputTypes.phone;
const field2: UserInput<InputTypes.email> = {
value: '',
type: InputTypes.email
};
// Error Type 'InputTypes.phone' is not assignable to type 'InputTypes.email'.
// field2.type = InputTypes.phone;
https://www.youtube.com/watch?v=eJ6R1knfsoc&t=1414s
type Diesel = { type: 'petroleum' | 'bio'}
type Gasoline = { type 'hybrid' | 'conentional'}
type Bus = { engine: Diesel }
type Car = { engine: Gasoline }
type Bicycle = { power: 'limbs' }
type Engine<T> = T extends { engine: unknown } ? T['engine'] : never;
const carEngine: Engine<Car> = {
type: 'hybrid'
}
// Engine<Bicycle> has a type of never
// Gets error 'only `never` can be assigned to `never`
const BikeEngine: Engine<Bicycle> = { power: 'limbs' };