1 of 60

2 of 60

About me

  • Tal Joffe
  • Web applications Director in Nielsen
  • Clean coder at heart
  • Wannabe functional programmer
  • Software design enthusiast

that’s me!

3 of 60

www.typescriptlang.org/docs

4 of 60

www.typescriptlang.org/docs

5 of 60

6 of 60

www.typescriptlang.org

7 of 60

www.typescriptlang.org

8 of 60

www.typescriptlang.org

9 of 60

🤔

Scale?�You mean like big data

10 of 60

Margaret Hamilton stands next to a stack of Apollo Guidance Computer source code.

Credits: MIT Museum

11 of 60

🙂

Gotcha.�So how do we make our code scale?

12 of 60

Scalable code

  • Code is readable
  • Structure is clear
  • Above is enforced

13 of 60

Scalable code

  • Code is readable
  • Structure is clear
  • Above is enforced

14 of 60

15 of 60

“The ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code. ...[Therefore,] making it easy to read makes it easier to write.”

― Robert C. Martin Clean Code: A Handbook of Agile Software Craftsmanship

16 of 60

17 of 60

18 of 60

🙄

Will you get to code examples at some point?

19 of 60

20 of 60

const getInformation = function(data) {

// ...

}

21 of 60

const getInformation = function(data) {

// ...

}

const getInformation = function(data: SegmentData): Information | undefined {

// ...

}

​

22 of 60

const getInformation = function(data) {

// ...

}

const getInformation = function(data: SegmentData): Information | undefined {

// ...

}

const getInformation = function(data: any): any {

// ...

}

23 of 60

24 of 60

class SegmentClassicOop extends BaseObject {

private name: string

private description: string

private folderId: number

private rule: Rule

private tenantId: number

​

public createSegment(name: string, description: string, folderId: number, ďż˝ rule: Rule, tenantId: number) {

if (name.length < 5){

throw new Error('segment name is invalid')

}

if (!this.isRuleValid(rule)){

throw new Error('segment must have valid rule')

}

if (!tenantId) {

throw new Error('segment must have valid rule')

}

}

// ... Other methods

// ... getters and setters

}

25 of 60

class SegmentOop extends BaseObject {

public name: string

public description: string

public folderId: number

public rule: Rule

public tenantId: number

}

​

class RuleValidator {

​

public ruleValidator(){

//implement rule validation

}

}

​

// ... other validators

26 of 60

type Segment = BaseObject & {

name: string;

description: string;

folderId: number;

rule: Rule;

tenantId: number;

}

​

function ruleValidator(rule: Rule): boolean {

// implement validation

}

​

27 of 60

28 of 60

Data objects go here

29 of 60

Data objects go here

Behavior is separated by who/what/how/where

30 of 60

31 of 60

type Props = {

a: number;

b: string;

}

​

const props: Props = {

a: 3,

b: 'ok',

c: 'not ok'

}

// TS2322: ... c does not exist in type Props

​

32 of 60

ReadOnly

type Todo = {

title: string;

}

​

const todo: Readonly<Todo> = {

title: "Delete inactive users"

}

​

todo.title = "Hello";

// Cannot assign to 'title' because it is a read-only property

​

33 of 60

Required

type Props = {

a?: number;

b?: string;

}

​

const obj: Props = { a: 5 };

​

const obj2: Required<Props> = { a: 5 };

// Property 'b' is missing in type '{ a: number; }' ďż˝// but required in type 'Required<Props>'

​

34 of 60

Pattern - CQS

�export interface Command<Entity>{

execute(argument: Entity): void

}

​

export interface Query<QueryParams,Entity>{

execute(queryParams: QueryParams): Promise<Entity[]>

}

ďż˝

35 of 60

Convention - Controller

export type ExpressFunc = (req: express.Request, ďż˝ res: express.Response,ďż˝ next: express.NextFunction) => Promise<express.Response>

​

​

export type controller = {

getSingle: ExpressFunc,

get: ExpressFunc,

post: ExpressFunc,

put: ExpressFunc,

delete: ExpressFunc,

bulkDelete: ExpressFunc,

bulkPost: ExpressFunc,

bulkPut: ExpressFunc

}

​

36 of 60

export function restController<Query,DTO,Entity>(

getMethod: query<Query, Entity>,

postMethod: command<Entity>,

putMethod: command<Entity>,

deleteMethod: command<Entity>,

converter: converter<DTO,Entity>): controller {

​

return {

getSingle: runQuerySingle<Query, DTO, Entity>(getMethod, converter),

get: runQuery<Query, DTO, Entity>(getMethod, converter),

post: executeCommand<DTO, Entity>(postMethod, converter),

put: executeCommand<DTO, Entity>(putMethod, converter),

delete : executeCommand<DTO, Entity>(deleteMethod, converter),

bulkDelete : executeBulkCommand<DTO, Entity>(deleteMethod, converter),

bulkPost: executeBulkCommand<DTO, Entity>(postMethod, converter),

bulkPut: executeBulkCommand<DTO, Entity>(putMethod, converter)

}

}

​

37 of 60

🤓

WOW! �Sounds Amazing

38 of 60

🧐

But wait.. �what about all the overhead typescript adds

39 of 60

Dealing with Overhead

  • Use type inference

40 of 60

Dealing with Overhead

  • Use type inference

const segment: Segment = getSegment(id)

​

const segment = getSegment(id)

​

41 of 60

Dealing with Overhead

  • Use type inference
  • Don’t over due OOP (“all you need is types” (-: )

42 of 60

Dealing with Overhead

  • Use type inference
  • Don’t over due OOP (“all you need is types” (-: )
  • KISS - don’t have too many patterns/convention

​

43 of 60

Dealing with Overhead

  • Use type inference
  • Don’t over due OOP (“all you need is types” (-: )
  • KISS - don’t have too many patterns/convention
  • You don’t have to create everything manually

​

44 of 60

Dealing with Overhead

  • Use type inference
  • Don’t over due OOP (“all you need is types” (-: )
  • KISS - don’t have too many patterns/convention
  • You don’t have to create everything manually
    • Union and Intersection
    • UtilityTypes and
    • TypeOf, KeyOf

45 of 60

type Segment = BaseObject & {

name: string;

description: string;

folderId: number;

rule: Rule;

tenantId: number;

}

​

function ruleValidator(rule: Rule): boolean {

// implement validation

}

​

46 of 60

enum ColorsEnum {

white = '#ffffff',

black = '#000000',

}

​

type Colors = keyof typeof ColorsEnum

​

let colorLiteral: Colors

colorLiteral = "white" // OK

colorLiteral = "black" // OK

colorLiteral = "red" // Error...

​

47 of 60

― redux.js.org/usage/usage-with-typescript

48 of 60

Scalability Test

  • You need to add a feature/fix a bug in a big project
    • Do you know exactly where to look in the project?
    • How confident you are it is working as expected?

49 of 60

😬

How confident?�Well I pray a lot before I deploy...

50 of 60

Trophy

Static

Unit

Integration

E2E

51 of 60

“TypeScript can catch errors and bugs at build time, long before your app goes live”

― https://reactjs.org/docs/static-type-checking

52 of 60

describe('segment use cases', () => {

​

test('should update segment', async () => {

const mockSegment = createMockSegment()

​

const savedSegmentId = await createSegment(mockSegment)

const savedSegment = await getSegment(mockSegment.savedSegmentId)

​

expect(savedSegment.name).toEqual(mockSegment.name)

expect(savedSegment.description).toEqual(mockSegment.description)

// you get the picture

})

//...more tests

​

53 of 60

describe('segment use cases', () => {

​

test('should update segment', async () => {

const mockSegment = createMockSegment()

​

const savedSegmentId = await createSegment(mockSegment)

const savedSegment = await getSegment(mockSegment.savedSegmentId)

​

expect(savedSegment.name).toEqual(mockSegment.name)

expect(savedSegment.description).toEqual(mockSegment.description)

// you get the picture

})

//...more tests

​

​

async function createMockSegment(): SegmentBO {

// …

}

​

54 of 60

Summary

  • By using types we can
    • Make our code more readable
    • Enforce order and structure
    • Have better confidence
  • There is an overhead but we can minimise it

55 of 60

All You Need is Types!

56 of 60

All You Need is Types!

(And Generics)

57 of 60

All You Need is Types!

(And Generics)

(And Unions/Intersections)

58 of 60

All You Need is Types!

(And Generics)

(And Unions/Intersections)

(And TypeUtils)

59 of 60

All You Need is Types!

(And Generics)

(And Unions/Intersections)

(And TypeUtils)

(And a couple of other stuff but you get the picture)

60 of 60

@TalJoffe