TypeScript. Часть II. Старков Дима

Size: px
Start display at page:

Download "TypeScript. Часть II. Старков Дима"

Transcription

1 TypeScript Часть II Старков Дима 1

2 Сегодня Вывод типов Структурная типизация Более сложные типы Обобщенные типы Type Guards 2

3 TypeScript? Спасет от выстрелов себе в ногу ESNext прямо сейчас Средство против TypeError Пишет код за вас Документация к коду Но... 3

4 4

5 Вывод типов let n: number = 42 let s: string = 'Hello, world!' let a: number[] = [1, 2, 3, 4] let n = 42 let s = 'Hello, world!' let a = [1, 2, 3, 4] 5

6 Наиболее общий тип let shapes = [new Circle(), new Square()] shapes.push(new Triangle()) 6

7 Наиболее общий тип let shapes = [new Circle(), new Square()] // Argument of type 'Triangle' // is not assignable to parameter of type 'Square Circle'. shapes.push( new Triangle() ) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 7

8 Наиболее общий тип let shapes = [new Circle(), new Square()] shapes.push(new Triangle()) 8

9 Наиболее общий тип let shapes = [new Circle(), new Square()] shapes.push(new Triangle()) 9

10 Наиболее общий тип let shapes = [new Circle(), new Square()] shapes.push(new Triangle()) 10

11 Наиболее общий тип let shapes = [new Circle(), new Square()] // Argument of type 'Triangle' // is not assignable to parameter of type 'Square Circle'. shapes.push( new Triangle() ) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 11

12 Наиболее общий тип let shapes: Shape[] = [new Circle(), new Square()] shapes.push(new Triangle()) 12

13 Совместимость типов class Human { name: string class Robot { name: string let human: Human = new Robot() 13

14 Проверка типа в runtime function addshape(shapes: Shape[], obj: object) { if (obj instanceof Shape) { shapes.push(obj as Shape) throw new TypeError('Argument is not instanceof Shape') 14

15 Проверка типа в runtime function addshape(shapes: Shape[], obj: object) { if (obj instanceof Shape) { shapes.push(obj as Shape) throw new TypeError('Argument is not instanceof Shape') 15

16 Проверка типа в runtime function addshape(shapes: Shape[], obj: object) { if (obj instanceof Shape) { shapes.push(obj as Shape) throw new TypeError('Argument is not instanceof Shape') 16

17 Проверка типа в runtime function addshape(shapes: Shape[], obj: object) { if (obj instanceof Shape) { shapes.push(obj as Shape) throw new TypeError('Argument is not instanceof Shape') 17

18 Проверка типа в runtime function addshape(shapes: Shape[], obj: object) { if (obj instanceof Shape) { shapes.push(obj as Shape) throw new TypeError('Argument is not instanceof Shape') 18

19 Type Guard function addshape(shapes: Shape[], obj: object) { if (obj instanceof Shape) { shapes.push(obj) throw new TypeError('Argument is not instanceof Shape') 19

20 TypeScript крут. Но можем ли мы описать весь JavaScript? 20

21 Вспомним TypeScript 1.0 Интерфейсы Классы Обобщенные типы Перегрузки функций Чего еще желать? 21

22 // String.split split(separator:?, limit: number): string[] 22

23 // String.split split(separator: string RegExp, limit: number): string[] 23

24 // String.split split(separator: string RegExp, limit: number): string[] Решение: Union Types 24

25 Union Type Guard function negate(n: string number) { if (typeof n === 'string') { return '-'.concat(n); else { return -n; 25

26 Union Type Guard function negate(n: string number) { if (typeof n === 'string') { return '-'.concat(n); else { return -n; 26

27 Union Type Guard function negate(n: string number) { if (typeof n === 'string') { return '-'.concat(n); else { return -n; 27

28 Union Type Guard function negate(n: string number) { if (typeof n === 'string') { return '-'.concat(n); else { return -n; 28

29 Union Type Guard function negate(n: string number) { if (typeof n === 'string') { return '-'.concat(n); return -n; 29

30 Intersection Types type Cat = { purr() 30

31 Intersection Types type Cat = { purr() type Dog = { woof() 31

32 Intersection Types type Cat = { purr() type Dog = { woof() type CatDog = Cat & Dog 32

33 Type Alias // String.split split(separator: string RegExp, limit: number): string[] 33

34 Type Alias type StringOrRegExp = string RegExp // String.split split(separator: StringOrRegExp, limit: number): string[] 34

35 Type vs Interface type Point = { x: number y: number interface Point { x: number y: number implements interface Type1 Type2 35

36 Тип Множество Можем объединять типы Можем пересекать типы & Можем вычитать из одного типа другой Фух, теперь точно всё... 36

37 А вот и нет! function get(obj, keyname) { return obj[keyname] function get(obj: any, keyname: string): any { return obj[keyname] // TypeError: Cannot read property 'prototype' of null get(null, 'prototype') 37

38 А вот и нет! function get(obj, keyname) { return obj[keyname] function get(obj: any, keyname: string): any { return obj[keyname] // TypeError: Cannot read property 'prototype' of null get(null, 'prototype') 38

39 А вот и нет! function get(obj, keyname) { return obj[keyname] function get(obj: any, keyname: string): any { return obj[keyname] // TypeError: Cannot read property 'prototype' of null get(null, 'prototype') 39

40 А вот и нет! function get(obj, keyname) { return obj[keyname] function get(obj: any, keyname: string): any { return obj[keyname] // TypeError: Cannot read property 'prototype' of null get(null, 'prototype') 40

41 Нужно уметь обрабатывать значения разных типов идентичным образом Кажется нам нужен... 41

42 42

43 Обобщенные типы function identity(arg: any): any { return arg; 43

44 Обобщенные типы function identity<t>(arg: T): T { return arg; 44

45 Обобщенные функции function identity<t>(arg: T): T { return arg; identity('string') // T is string identity( ) // T is number identity([4, 8, 15, 16, 23, 42]) // T is number[] 45

46 Встроенные обобщенные типы const fib: Array<number> = [1, 1, 2, 3, 5] // Argument of type 'string' // is not assignable to parameter of type 'number'. fib.push( '1') ~~~~~~~~~ const map: Map<number, string> = new Map() // Argument of type 'number' // is not assignable to parameter of type 'string'. map.set(1, ) 1~~~ 46

47 Обобщенные интерфейсы interface IStack<TItem> { push(item: TItem) pop(): TItem let numstack: IStack<number> = [1, 2, 3] 47

48 Обобщенные интерфейсы interface IStack<number> { push(item: number) pop(): number let numstack: IStack<number> = [1, 2, 3] 48

49 Обобщенные типы type AsyncResult<TResult> = Promise<TResult> TResult let result: AsyncResult<string> = Promise.resolve('200') let result: AsyncResult<string> = '200' 49

50 Обобщенные типы type AsyncResult<string> = Promise<string> string let result: AsyncResult<string> = Promise.resolve('200') let result: AsyncResult<string> = '200' 50

51 Обобщенные классы class Stack<TItem> implements IStack<TItem> { private state: TItem[] constructor() { this.state = [] push(item: TItem) { this.state.push(item) pop(): TItem { return this.state.pop() 51

52 Обобщенные классы class Stack<TItem> implements IStack<TItem> { private state: TItem[] = [] push(item: TItem) { this.state.push(item) pop(): TItem { return this.state.pop() 52

53 Обобщенные типы interface ISwim { swim() class Dog implements ISwim { swim() {... class Duck implements ISwim { swim() {... 53

54 Ограничения на обобщенные типы function swimtogether< T1 implements ISwim, T2 implements ISwim >(firstpal: T1, secondpal: T2) { firstpal.swim() secondpal.swim() 54

55 55

56 Обобщенные типы type TypeName<T> = T extends string? 'string' : T extends number? 'number' : T extends boolean? 'boolean' : T extends undefined? 'undefined' : T extends Function? 'function' : 'object' 56

57 Обобщенные типы type TypeName<string> = string extends string? 'string' : T extends number? 'number' : T extends boolean? 'boolean' : T extends undefined? 'undefined' : T extends Function? 'function' : 'object' 57

58 Обобщенные типы type TypeName<number> = number extends string? 'string' : number extends number? 'number' : T extends boolean? 'boolean' : T extends undefined? 'undefined' : T extends Function? 'function' : 'object' 58

59 Наша функция function get(obj: any, keyname: string): any { return obj[keyname] 59

60 Наша функция function get<t>(obj: T, keyname: string): any { return obj[keyname] 60

61 Хотим знать список полей объекта и их типы на этапе компиляции Решение: Lookup Types и keyof 61

62 Lookup типы interface IUser { login: string age: number gender: 'male' 'female' let login: IUser['login'] let login: string let loginorage: IUser['login' 'age'] let loginorage: string number 62

63 keyof interface IUser { login: string age: number gender: 'male' 'female' let key: keyof IUser let key: 'login' 'age' 'gender' 63

64 Наша простая функция function get(obj, keyname) { return obj[keyname] 64

65 Наша простая функция function get<t>(obj: T, keyname: keyof T): T[keyof T] { return obj[keyname] 65

66 Наша простая функция function get<t>(obj: T, keyname: keyof T): T[keyof T] { return obj[keyname] let a: number = get({ a: 1, 'a') 66

67 Наша простая функция function get<{ a: 1 >(obj: T, keyname: keyof T): T[keyof T] { return obj[keyname] let a: number = get({ a: 1, 'a') 67

68 Наша простая функция function get<{ a: 1 >(obj: T, keyname: 'a'): T['a'] { return obj[keyname] let a: number = get({ a: 1, 'a') 68

69 Наша простая функция function get<{ a: 1 >(obj: T, keyname: 'a'): number { return obj[keyname] let a: number = get({ a: 1, 'a') 69

70 Наша простая функция function get<t>(obj: T, keyname: keyof T): T[keyof T] { return obj[keyname] let a: number = get({ a: 1, 'a') // Argument of type '"c"' // is not assignable to parameter of type '"a" "b"'. let c: undefined = get({ a: 1, b: 2, 'c') ~~~~~~~~~ 70

71 Наша простая функция function get<t, K extends keyof T>(obj: T, keyname: K): T[K] { return obj[keyname] let a: number = get({ a: 1, 'a') let c: undefined = get({ a: 1, b: 2, 'c') 71

72 Перерыв 72

73 А что там в es5? interface IUser { login: string age: number gender: 'male' 'female' const user = { login: 'dimastark', age: 21, gender: 'male' const readonlyuser:? = Object.freeze(user) 73

74 А что там в es5? interface IFrozenUser { readonly login: string readonly age: number readonly gender: 'male' 'female' const user = { login: 'dimastark', age: 21, gender: 'male' const readonlyuser: IFrozenUser = Object.freeze(user) Решение: Mapped Types 74

75 75

76 Mapped Types interface IUser { login: string age: number gender: 'male' 'female' type Readonly<T> = { ; readonly [P in 'login' 'age' 'gender']: T[P]; const user = { login: 'dimastark', age: 21, gender: 'male' const readonlyuser: Readonly<IUser> = Object.freeze(user) 76

77 Mapped Types + keyof interface IUser { login: string age: number gender: 'male' 'female' type Readonly<T> = { ; readonly [P in keyof T]: T[P]; const user = { login: 'dimastark', age: 21, gender: 'male' const readonlyuser: Readonly<IUser> = Object.freeze(user) 77

78 infer type ValueOf<T> = T extends { [key: string]: infer U? U : never; ValueOf<{ a: string, b: string > // string ValueOf<{ a: string, b: number > // string number 78

79 Mapped Types interface IUser { login: string birthdate: { year: number month: number day: number gender: 'male' 'female' 79

80 Mapped Types type DeepReadonly<T> = { [P in keyof T]: T[P] extends (infer U)[]? DeepReadonly<U>[] : T[P] extends object? DeepReadonly<T[P]> : readonly T[P]; ; 80

81 Mapped Types type DeepReadonly<T> = { [P in keyof T]: T[P] extends (infer U)[]? DeepReadonly<U>[] : T[P] extends object? DeepReadonly<T[P]> : readonly T[P]; ; 81

82 Mapped Types type DeepReadonly<T> = { [P in keyof T]: T[P] extends (infer U)[]? DeepReadonly<U>[] : T[P] extends object? DeepReadonly<T[P]> : readonly T[P]; ; 82

83 Mapped Types type DeepReadonly<T> = { [P in keyof T]: T[P] extends (infer U)[]? DeepReadonly<U>[] : T[P] extends object? DeepReadonly<T[P]> : readonly T[P]; ; 83

84 Mapped Types type DeepReadonly<T> = { [P in keyof T]: T[P] extends (infer U)[]? DeepReadonly<U>[] : T[P] extends object? DeepReadonly<T[P]> : readonly T[P]; ; 84

85 Mapped Types type DeepReadonly<T> = { [P in keyof T]: T[P] extends (infer U)[]? DeepReadonly<U>[] : T[P] extends object? DeepReadonly<T[P]> : readonly T[P]; ; 85

86 Mapped Types type DeepReadonly<T> = { [P in keyof T]: T[P] extends (infer U)[]? DeepReadonly<U>[] : T[P] extends object? DeepReadonly<T[P]> : readonly T[P]; ; 86

87 Mapped Types type DeepReadonly<T> = { [P in keyof T]: T[P] extends (infer U)[]? DeepReadonly<U>[] : T[P] extends object? DeepReadonly<T[P]> : readonly T[P]; ; 87

88 Mapped Types type DeepReadonly<T> = { [P in keyof T]: T[P] extends (infer U)[]? DeepReadonly<U>[] : T[P] extends object? DeepReadonly<T[P]> : readonly T[P]; ; 88

89 Ссылочки TypeScript Handbook. Advanced. TypeScript Deep Dive Андрей Старовойт Эволюция TypeScript TypeScript Playground 89

90 Вопросы? 90

91 Спасибо! 91

Nick Senger & Jesse van den Kieboom

Nick Senger & Jesse van den Kieboom Using TypeScript with the ArcGIS API for JavaScript Nick Senger & Jesse van den Kieboom Live version of this presentation is available on: https://jkieboom.github.io/devsummit-palm-springs-2018/presentations/typescript-arcgis-js-api

More information

ОБЪЕКТНО- ОРИЕНТИРОВАННОЕ ПРОГРАММИРОВАНИЕ. Лекция 1 / г.

ОБЪЕКТНО- ОРИЕНТИРОВАННОЕ ПРОГРАММИРОВАНИЕ. Лекция 1 / г. ОБЪЕКТНО- ОРИЕНТИРОВАННОЕ ПРОГРАММИРОВАНИЕ Лекция 1 / 04 04.03.2019 г. VIRTUAL DESTRUCTOR class Shape{ int x, y; Shape(int x, int y); ~Shape(){ printf("dtor shape!\n"); class Circle: public Shape{ int

More information

JavaScript Lecture 2

JavaScript Lecture 2 JavaScript Lecture 2 Waterford Institute of Technology May 5, 2016 John Fitzgerald Waterford Institute of Technology, JavaScriptLecture 2 1/28 JavaScript Introduction Topics discussed this presentation

More information

TypeScript. Jonathan Kula 12/3/2018

TypeScript. Jonathan Kula 12/3/2018 TypeScript Jonathan Kula 12/3/2018 Introducing TypeScript A superset of JavaScript. This means that all JavaScript code is valid TypeScript code! TypeScript just adds some new features that will make your

More information

COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts

COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

An Introduction to TypeScript. Personal Info

An Introduction to TypeScript. Personal Info An Introduction to TypeScript Jason Bock Practice Lead Magenic Level: Beginner/Intermediate Personal Info http://www.magenic.com http://www.jasonbock.net https://www.twitter.com/jasonbock https://www.github.com/jasonbock

More information

Client-Side Web Technologies. JavaScript Part I

Client-Side Web Technologies. JavaScript Part I Client-Side Web Technologies JavaScript Part I JavaScript First appeared in 1996 in Netscape Navigator Main purpose was to handle input validation that was currently being done server-side Now a powerful

More information

JavaScript: Sort of a Big Deal,

JavaScript: Sort of a Big Deal, : Sort of a Big Deal, But Sort of Quirky... March 20, 2017 Lisp in C s Clothing (Crockford, 2001) Dynamically Typed: no static type annotations or type checks. C-Like Syntax: curly-braces, for, semicolons,

More information

TypeScript. Types. CS144: Web Applications

TypeScript. Types. CS144: Web Applications TypeScript Superset of JavaScript (a.k.a. JavaScript++) to make it easier to program for largescale JavaScript projects New features: types, interfaces, decorators,... All additional TypeScript features

More information

Symbols. accessor properties, attributes, creating, adding properties, 8 anonymous functions, 20, 80

Symbols. accessor properties, attributes, creating, adding properties, 8 anonymous functions, 20, 80 Index Symbols { } (braces) for function contents, 18 and object properties, 9 == (double equals operator), 5 === (triple equals operator), 5 [ ] (square brackets) for array literals, 10 for property access,

More information

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Collaboration and Management Dana Fisman Lesson 2 - Types with TypeScript 1 Types What are types in programming languages? What types are you

More information

Карта «Кофейные регионы Эфиопии» Коллеги из Trabocca любезно предоставили нам карту кофейных регионов Эфиопии, за что

Карта «Кофейные регионы Эфиопии» Коллеги из Trabocca любезно предоставили нам карту кофейных регионов Эфиопии, за что 19 Февраля 2019 Карта «Кофейные регионы Эфиопии» Коллеги из Trabocca любезно предоставили нам карту кофейных регионов Эфиопии, за что большое им спасибо! Целью создания карты была ощутимая прослеживаемость

More information

COMPUTER APPLICATIONS

COMPUTER APPLICATIONS COMPUTER APPLICATIONS (Theory) (Two hours) Answers to this Paper must be written on the paper provided separately. You will not be allowed to write during the first 15 minutes. This time is to be spent

More information

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More information

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Using pointers Pointers are polymorphic Pointer this Using const with pointers Stack and Heap Memory leaks and dangling pointers

More information

3/6/2018 Spectacle PARALLELIZING PRODUCT DEVELOPMENT WITH GRAPHQL.

3/6/2018 Spectacle PARALLELIZING PRODUCT DEVELOPMENT WITH GRAPHQL. @chrisbiscardi PARALLELIZING PRODUCT DEVELOPMENT WITH GRAPHQL http://localhost:3000/#/6?export 1/48 honeycomb.io coffee @chrisbiscardi biscarch CHRISBISCARDI http://localhost:3000/#/6?export 2/48 APPLICATION

More information

Announcements/Follow-ups

Announcements/Follow-ups Announcements/Follow-ups Midterm #2 Friday Everything up to and including today Review section tomorrow Study set # 6 online answers posted later today P5 due next Tuesday A good way to study Style omit

More information

Object Oriented Programming 2015/16. Final Exam June 28, 2016

Object Oriented Programming 2015/16. Final Exam June 28, 2016 Object Oriented Programming 2015/16 Final Exam June 28, 2016 Directions (read carefully): CLEARLY print your name and ID on every page. The exam contains 8 pages divided into 4 parts. Make sure you have

More information

Introduction to Java https://tinyurl.com/y7bvpa9z

Introduction to Java https://tinyurl.com/y7bvpa9z Introduction to Java https://tinyurl.com/y7bvpa9z Eric Newhall - Laurence Meyers Team 2849 Alumni Java Object-Oriented Compiled Garbage-Collected WORA - Write Once, Run Anywhere IDE Integrated Development

More information

TypeScript für Fortgeschrittene

TypeScript für Fortgeschrittene TypeScript für Fortgeschrittene Tobias Meier, BridgingIT GmbH http://blog.bridging-it.de/author/tobias.meier Tobias Meier Lead Softwarearchitekt Microsoft Blog: http://blog.bridging-it.de/author/tobias.meier

More information

Object Oriented Programming Part I of II. Steve Ryder 08/22/05, Session 8351 JSR Systems (JSR)

Object Oriented Programming Part I of II. Steve Ryder 08/22/05, Session 8351 JSR Systems (JSR) Object Oriented Programming Part I of II Steve Ryder 08/22/05, Session 8351 JSR Systems (JSR) sryder@jsrsys.com Objectives Compare/Contrast OO Programming to Procedural Programming Introduction to these

More information

TypeScript. TypeScript. RxJS

TypeScript. TypeScript. RxJS Web 2017.08 About Me TypeScript TypeScript RxJS 2014 X 4 0 Mac/Windows Native UI Web Angular React JavaScript IM User DING Contact RPC Native Nw.js C++ Cef 2014 10 Web 11 nw.js Web App IM DING DING ->

More information

AP CS Unit 6: Inheritance Notes

AP CS Unit 6: Inheritance Notes AP CS Unit 6: Inheritance Notes Inheritance is an important feature of object-oriented languages. It allows the designer to create a new class based on another class. The new class inherits everything

More information

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring

More information

MatchaScript: Language Reference Manual Programming Languages & Translators Spring 2017

MatchaScript: Language Reference Manual Programming Languages & Translators Spring 2017 MatchaScript: Language Reference Manual Programming Languages & Translators Spring 2017 Language Guru: Kimberly Hou - kjh2146 Systems Architect: Rebecca Mahany - rlm2175 Manager: Jordi Orbay - jao2154

More information

ANSWER KEY. Study Guide. Completely fill in the box corresponding to your answer choice for each question.

ANSWER KEY. Study Guide. Completely fill in the box corresponding to your answer choice for each question. CS 1331 Final Exam Study Guide ANSWER KEY Completely fill in the box corresponding to your answer choice for each question. 1. [ B ] [ C ] [ D ] 2. [ B ] [ C ] [ D ] 3. [ B ] [ C ] [ D ] 4. [ B ] [ C ]

More information

Java Programming. Atul Prakash

Java Programming. Atul Prakash Java Programming Atul Prakash Java Language Fundamentals The language syntax is similar to C/ C++ If you know C/C++, you will have no trouble understanding Java s syntax If you don't, it will be easier

More information

AP CS Unit 6: Inheritance Exercises

AP CS Unit 6: Inheritance Exercises AP CS Unit 6: Inheritance Exercises 1. Suppose your program contains two classes: a Student class and a Female class. Which of the following is true? a) Making the Student class a subclass of the Female

More information

Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p.

Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p. Preface p. xiii Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p. 5 Client-Side JavaScript: Executable Content

More information

TypeScript. Language Specification. Version 1.8

TypeScript. Language Specification. Version 1.8 TypeScript Language Specification Version 1.8 January, 2016 Microsoft is making this Specification available under the Open Web Foundation Final Specification Agreement Version 1.0 ("OWF 1.0") as of October

More information

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COE318 Lecture Notes Week 10 (Nov 7, 2011) COE318 Software Systems Lecture Notes: Week 10 1 of 5 COE318 Lecture Notes Week 10 (Nov 7, 2011) Topics More about exceptions References Head First Java: Chapter 11 (Risky Behavior) The Java Tutorial:

More information

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions C++: Const Function Overloading Constructors and Destructors Enumerations Assertions Const const float pi=3.14159; const int* pheight; // defines pointer to // constant int value cannot be changed // pointer

More information

Introduction to Web Tech and Programming

Introduction to Web Tech and Programming Introduction to Web Tech and Programming Objects Objects Arrays JavaScript Objects Objects are an unordered collection of properties. Basically variables holding variables. Have the form name : value name

More information

CS 1331 Exam 1 ANSWER KEY

CS 1331 Exam 1 ANSWER KEY CS 1331 Exam 1 Fall 2016 ANSWER KEY Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score. Signing signifies you are aware of and in

More information

JScript Reference. Contents

JScript Reference. Contents JScript Reference Contents Exploring the JScript Language JScript Example Altium Designer and Borland Delphi Run Time Libraries Server Processes JScript Source Files PRJSCR, JS and DFM files About JScript

More information

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript Program Structure function sqr(i) var result; // Otherwise result would be global. result = i * i; //

More information

B l o c k B i n d i n g s

B l o c k B i n d i n g s 1 Block Bindings Traditionally, the way variable declarations work has been one tricky part of programming in JavaScript. In most C-based languages, variables (more formally known as bindings, as a name

More information

Inheritance. CSE 142, Summer 2002 Computer Programming 1.

Inheritance. CSE 142, Summer 2002 Computer Programming 1. Inheritance CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 29-July-2002 cse142-14-inheritance 2002 University of Washington 1 Reading Readings and

More information

ADsafety. Type-based Verification of JavaScript Sandboxing. Joe Gibbs Politz Spiridon Aristides Eliopoulos Arjun Guha Shriram Krishnamurthi

ADsafety. Type-based Verification of JavaScript Sandboxing. Joe Gibbs Politz Spiridon Aristides Eliopoulos Arjun Guha Shriram Krishnamurthi ADsafety Type-based Verification of JavaScript Sandboxing Joe Gibbs Politz Spiridon Aristides Eliopoulos Arjun Guha Shriram Krishnamurthi 1 2 3 third-party ad third-party ad 4 Who is running code in your

More information

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations. Data Structures 1 Data structures What is a data structure? Simple answer: a collection of data equipped with some operations. Examples Lists Strings... 2 Data structures In this course, we will learn

More information

Typen nach JavaScript tragen TypeScript. Johannes Dienst

Typen nach JavaScript tragen TypeScript. Johannes Dienst Typen nach JavaScript tragen TypeScript Johannes Dienst Probleme von JavaScript JavaScript (kurz JS) ist eine Skriptsprache, die ursprünglich für dynamisches HTML in Webbrowsern entwickelt wurde[...] Quelle:

More information

Common Misunderstandings from Exam 1 Material

Common Misunderstandings from Exam 1 Material Common Misunderstandings from Exam 1 Material Kyle Dewey Stack and Heap Allocation with Pointers char c = c ; char* p1 = malloc(sizeof(char)); char** p2 = &p1; Where is c allocated? Where is p1 itself

More information

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger.

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS61B Fall 2015 P. N. Hilfinger Test #1 READ THIS PAGE FIRST. Please do not discuss this exam

More information

Midterm Exam. 5. What is the character - (minus) used for in JavaScript? Give as many answers as you can.

Midterm Exam. 5. What is the character - (minus) used for in JavaScript? Give as many answers as you can. First Name Last Name CSCi 90.3 March 23, 2010 Midterm Exam Instructions: For multiple choice questions, circle the letter of the one best choice unless the question explicitly states that it might have

More information

AP CS Unit 8: Inheritance Exercises

AP CS Unit 8: Inheritance Exercises AP CS Unit 8: Inheritance Exercises public class Animal{ System.out.print("A"); public void m2(){ System.out.print("B"); public class Dog extends Animal{ System.out.print("C"); public void m3(){ System.out.print("D");

More information

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed 1 1 COMP200 INHERITANCE OOP using Java, from slides by Shayan Javed 2 Inheritance Derive new classes (subclass) from existing ones (superclass). Only the Object class (java.lang) has no superclass Every

More information

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic BIT 3383 Java Programming Sem 1 Session 2011/12 Chapter 2 JAVA basic Objective: After this lesson, you should be able to: declare, initialize and use variables according to Java programming language guidelines

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Ruby: Objects and Dynamic Types

Ruby: Objects and Dynamic Types Ruby: Objects and Dynamic Types Computer Science and Engineering College of Engineering The Ohio State University Lecture 5 Primitive vs Reference Types Recall Java type dichotomy: Primitive: int, float,

More information

Lecture 10. Overriding & Casting About

Lecture 10. Overriding & Casting About Lecture 10 Overriding & Casting About Announcements for This Lecture Readings Sections 4.2, 4.3 Prelim, March 8 th 7:30-9:30 Material up to next Tuesday Sample prelims from past years on course web page

More information

The results for a few specific cases below are indicated. allequal ([1,1,1,1]) should return true allequal ([1,1,2,1]) should return false

The results for a few specific cases below are indicated. allequal ([1,1,1,1]) should return true allequal ([1,1,2,1]) should return false Test 1 Multiple Choice. Write your answer to the LEFT of each problem. 4 points each 1. Which celebrity has not received an ACM Turing Award? A. Alan Kay B. John McCarthy C. Dennis Ritchie D. Bjarne Stroustrup

More information

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies Internet t Software Technologies JavaScript part one IMCNE A.A. 2008/09 Gabriele Cecchetti Why introduce JavaScript To add dynamicity and interactivity to HTML pages 2 What s a script It s a little interpreted

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

JavaScript for C# Programmers Kevin

JavaScript for C# Programmers Kevin JavaScript for C# Programmers Kevin Jones kevin@rocksolidknowledge.com @kevinrjones http://www.github.com/kevinrjones Agenda Types Basic Syntax Objects Functions 2 Basics 'C' like language braces brackets

More information

MSc/ICY Software Workshop Exception Handling, Assertions Scanner, Patterns File Input/Output

MSc/ICY Software Workshop Exception Handling, Assertions Scanner, Patterns File Input/Output MSc/ICY Software Workshop Exception Handling, Assertions Scanner, Patterns File Input/Output Manfred Kerber www.cs.bham.ac.uk/~mmk 21 October 2015 1 / 18 Manfred Kerber Classes and Objects The information

More information

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle CS112-2012S-23 Abstract Classes and Interfaces 1 23-0: Drawing Example Creating a drawing program Allow user to draw triangles, circles, rectanlges, move them around, etc. Need to store a list of shapes,

More information

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals CS/ENGRD 2110 FALL 2018 Lecture 6: Consequence of type, casting; function equals http://courses.cs.cornell.edu/cs2110 Overview references in 2 Quick look at arrays: array Casting among classes cast, object-casting

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Informatik II (D-ITET) Tutorial 6

Informatik II (D-ITET) Tutorial 6 Informatik II (D-ITET) Tutorial 6 TA: Marian George, E-mail: marian.george@inf.ethz.ch Distributed Systems Group, ETH Zürich Exercise Sheet 5: Solutions and Remarks Variables & Methods beginwithlowercase,

More information

Powerful JavaScript OOP concept here and now. CoffeeScript, TypeScript, etc

Powerful JavaScript OOP concept here and now. CoffeeScript, TypeScript, etc Powerful JavaScript OOP concept here and now. CoffeeScript, TypeScript, etc JavaScript EasyOOP Inheritance, method overriding, constructor, anonymous classes, mixing, dynamic class extending, packaging,

More information

JavaScript. Training Offer for JavaScript Introduction JavaScript. JavaScript Objects

JavaScript. Training Offer for JavaScript Introduction JavaScript. JavaScript Objects JavaScript CAC Noida is an ISO 9001:2015 certified training center with professional experience that dates back to 2005. The vision is to provide professional education merging corporate culture globally

More information

What if Type Systems were more like Linters?

What if Type Systems were more like Linters? Typed Clojure An optional type system for Clojure What if Type Systems were more like Linters? Ambrose Bonnaire-Sergeant Me A Practical Optional Type System for Clojure (2012) Typed Clojure Indiegogo Campaign

More information

Experimental New Directions for JavaScript

Experimental New Directions for JavaScript Experimental New Directions for JavaScript Andreas Rossberg, V8/Google Motivation Broad need for (more) scalable JavaScript Usability, esp. maintainability Performance, esp. predictability ES6 opens up

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Variables and Typing

Variables and Typing Variables and Typing Christopher M. Harden Contents 1 The basic workflow 2 2 Variables 3 2.1 Declaring a variable........................ 3 2.2 Assigning to a variable...................... 4 2.3 Other

More information

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4 CS32 - Week 4 Umut Oztok Jul 15, 2016 Inheritance Process of deriving a new class using another class as a base. Base/Parent/Super Class Derived/Child/Sub Class Inheritance class Animal{ Animal(); ~Animal();

More information

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ Test 2. Question Max Mark Internal External

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ Test 2. Question Max Mark Internal External Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2009 Test 2 Question Max Mark Internal

More information

Crash Course Review Only. Please use online Jasmit Singh 2

Crash Course Review Only. Please use online Jasmit Singh 2 @ Jasmit Singh 1 Crash Course Review Only Please use online resources @ Jasmit Singh 2 Java is an object- oriented language Structured around objects and methods A method is an action or something you

More information

JavaScript: Features, Trends, and Static Analysis

JavaScript: Features, Trends, and Static Analysis JavaScript: Features, Trends, and Static Analysis Joonwon Choi ROPAS Show & Tell 01/25/2013 1 Contents What is JavaScript? Features Trends Static Analysis Conclusion & Future Works 2 What is JavaScript?

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 FALL 2017 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due tomorrow night (17 February) Get started on A3 a method every other day.

More information

Objects. say something to express one's disapproval of or disagreement with something.

Objects. say something to express one's disapproval of or disagreement with something. Objects say something to express one's disapproval of or disagreement with something. class Person: def init (self, name, age): self.name = name self.age = age p1 = Person("John", 36) class Person: def

More information

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 4 - Type Checking Collaboration and Management Dana Fisman 1 Why declare types? Declaring types allows the compiler to detect errors

More information

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller Inheritance & Abstract Classes 15-121 Margaret Reid-Miller Today Today: Finish circular queues Exercise: Reverse queue values Inheritance Abstract Classes Clone 15-121 (Reid-Miller) 2 Object Oriented Programming

More information

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications JavaScript Started as a simple script in a Web page that is interpreted and run by the browser Supported by most modern browsers Allows dynamic update of a web page More generally, allows running an arbitrary

More information

Ch02. True/False Indicate whether the statement is true or false.

Ch02. True/False Indicate whether the statement is true or false. Ch02 True/False Indicate whether the statement is true or false. 1. The base class inherits all its properties from the derived class. 2. Inheritance is an is-a relationship. 3. In single inheritance,

More information

Checking Multiple Conditions

Checking Multiple Conditions Checking Multiple Conditions Conditional code often relies on a value being between two other values Consider these conditions: Free shipping for orders over $25 10 items or less Children ages 3 to 11

More information

Name:... ID:... class A { public A() { System.out.println( "The default constructor of A is invoked"); } }

Name:... ID:... class A { public A() { System.out.println( The default constructor of A is invoked); } } KSU/CCIS/CS CSC 113 Final exam - Fall 12-13 Time allowed: 3:00 Name:... ID:... EXECRICE 1 (15 marks) 1.1 Write the output of the following program. Output (6 Marks): class A public A() System.out.println(

More information

CSC Java Programming, Fall Java Data Types and Control Constructs

CSC Java Programming, Fall Java Data Types and Control Constructs CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference

More information

UMBC CMSC 331 Final Exam

UMBC CMSC 331 Final Exam UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy

More information

Building Your own Widget with ArcGIS API for JavaScript

Building Your own Widget with ArcGIS API for JavaScript Building Your own Widget with ArcGIS API for JavaScript Matt Driscoll @driskull JC Franco @arfncode Agenda About Widgets Prerequisites Widget framework Theming DO IT! Tips & tricks About Widgets What?

More information

One language to rule them all: TypeScript. Gil Fink CEO and Senior Consultant, sparxys

One language to rule them all: TypeScript. Gil Fink CEO and Senior Consultant, sparxys One language to rule them all: TypeScript Gil Fink CEO and Senior Consultant, sparxys About Me sparxys CEO and Senior consultant Microsoft MVP in the last 8 years Pro Single Page Application Development

More information

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications JavaScript CS 4640 Programming Languages for Web Applications 1 How HTML, CSS, and JS Fit Together {css} javascript() Content layer The HTML gives the page structure and adds semantics Presentation

More information

iwiki Documentation Release 1.0 jch

iwiki Documentation Release 1.0 jch iwiki Documentation Release 1.0 jch January 31, 2014 Contents i ii Contents: Contents 1 2 Contents CHAPTER 1 Python 1.1 Python Core 1.1.1 Strings 1.1.2 Functions Argument Lists *args tuple/list **kwargs

More information

Variable Declarations

Variable Declarations Variable Declarations Variables can be declared using var or the newer let. Note that declaration is simply var x = 1 or let x = 1; there is no type as js variables do not have types. Constant variables

More information

Create a Questionnaire. Triangle

Create a Questionnaire. Triangle Create a Questionnaire Triangle 1. Access EyeQuestion Open your browser (e.g. Internet Explorer) Browse to your EyeQuestion server The login screen will be visible 2. Login Login with your credentials

More information

UNIT -II. Language-History and Versions Introduction JavaScript in Perspective-

UNIT -II. Language-History and Versions Introduction JavaScript in Perspective- UNIT -II Style Sheets: CSS-Introduction to Cascading Style Sheets-Features- Core Syntax-Style Sheets and HTML Style Rle Cascading and Inheritance-Text Properties-Box Model Normal Flow Box Layout- Beyond

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 4 (a): Classes & Objects Lecture Contents 2 What is a class? Class definition: Data Methods Constructors objects Static members

More information

Classes vs Simple Object Delegation In JavaScript

Classes vs Simple Object Delegation In JavaScript Classes vs Simple Object Delegation In JavaScript Things to consider... Do we want to (deeply) understand what our code is doing? Do we want encapsulation? Do we want true private variables and functions?

More information

Proxies Design Principles for Robust OO Intercession APIs

Proxies Design Principles for Robust OO Intercession APIs Proxies Design Principles for Robust OO Intercession APIs Tom Van Cutsem Mark S. Miller Overview Context: a new -programming API for Javascript (d on ECMAScript 5th ed.) Focus on intercession, intercepting

More information

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass Inheritance and Polymorphism Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism Inheritance (semantics) We now have two classes that do essentially the same thing The fields are exactly

More information

Computer Science II (20082) Week 1: Review and Inheritance

Computer Science II (20082) Week 1: Review and Inheritance Computer Science II 4003-232-08 (20082) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Syntax and Semantics of Formal (e.g. Programming) Languages Syntax

More information

The course is supplemented by numerous hands-on labs that help attendees reinforce their theoretical knowledge of the learned material.

The course is supplemented by numerous hands-on labs that help attendees reinforce their theoretical knowledge of the learned material. Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA2442 Introduction to JavaScript Objectives This intensive training course

More information

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters. CISC-124 20180215 These notes are intended to summarize and clarify some of the topics that have been covered recently in class. The posted code samples also have extensive explanations of the material.

More information