0% found this document useful (0 votes)
44 views

Programming TypeScript Making Your JavaScript Applications Scale 1st Edition Boris Cherny - Own the ebook now with all fully detailed chapters

The document promotes the ebook 'Programming TypeScript: Making Your JavaScript Applications Scale' by Boris Cherny, available for download at ebookmeta.com. It includes a detailed table of contents outlining various topics related to TypeScript, such as types, functions, classes, error handling, and asynchronous programming. The book aims to provide both theoretical understanding and practical advice for programmers of all backgrounds to effectively use TypeScript.

Uploaded by

ausejobeeton
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Programming TypeScript Making Your JavaScript Applications Scale 1st Edition Boris Cherny - Own the ebook now with all fully detailed chapters

The document promotes the ebook 'Programming TypeScript: Making Your JavaScript Applications Scale' by Boris Cherny, available for download at ebookmeta.com. It includes a detailed table of contents outlining various topics related to TypeScript, such as types, functions, classes, error handling, and asynchronous programming. The book aims to provide both theoretical understanding and practical advice for programmers of all backgrounds to effectively use TypeScript.

Uploaded by

ausejobeeton
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

Programming TypeScript Making Your JavaScript


Applications Scale 1st Edition Boris Cherny

https://ebookmeta.com/product/programming-typescript-making-
your-javascript-applications-scale-1st-edition-boris-cherny/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Programming TypeScript Making Your JavaScript Applications


Scale 1st Edition Boris Cherny

https://ebookmeta.com/product/programming-typescript-making-your-
javascript-applications-scale-1st-edition-boris-cherny/

ebookmeta.com

Learning TypeScript: Enhance Your Web Development Skills


Using Type-Safe JavaScript Josh Goldberg

https://ebookmeta.com/product/learning-typescript-enhance-your-web-
development-skills-using-type-safe-javascript-josh-goldberg-2/

ebookmeta.com

Learning TypeScript: Enhance Your Web Development Skills


Using Type-Safe JavaScript Josh Goldberg

https://ebookmeta.com/product/learning-typescript-enhance-your-web-
development-skills-using-type-safe-javascript-josh-goldberg/

ebookmeta.com

The Shakespearean Inside A Study of the Complete


Soliloquies and Solo Asides 1st Edition Marcus Nordlund

https://ebookmeta.com/product/the-shakespearean-inside-a-study-of-the-
complete-soliloquies-and-solo-asides-1st-edition-marcus-nordlund/

ebookmeta.com
The Dutch East India Company Captivating History

https://ebookmeta.com/product/the-dutch-east-india-company-
captivating-history/

ebookmeta.com

When the Smoke Cleared Attica Prison Poems and Journal 1st
Edition Celes Tisdale

https://ebookmeta.com/product/when-the-smoke-cleared-attica-prison-
poems-and-journal-1st-edition-celes-tisdale/

ebookmeta.com

Dorsolateral Prefrontal Cortex Working Memory and


Executive Functions 1st Edition Shintaro Funahashi

https://ebookmeta.com/product/dorsolateral-prefrontal-cortex-working-
memory-and-executive-functions-1st-edition-shintaro-funahashi/

ebookmeta.com

A Different Look at Artificial Intelligence On Tour with


Bergson Proust and Nabokov 1st Edition Ulrike Barthelmeß

https://ebookmeta.com/product/a-different-look-at-artificial-
intelligence-on-tour-with-bergson-proust-and-nabokov-1st-edition-
ulrike-barthelmes/
ebookmeta.com

Everyday Go The Fast Track for Golang Alex Ellis

https://ebookmeta.com/product/everyday-go-the-fast-track-for-golang-
alex-ellis/

ebookmeta.com
PCEP Book 1 Maternal and Fetal Evaluation and Immediate
Newborn Care Robert A Sinkin (Editor In Chief)

https://ebookmeta.com/product/pcep-book-1-maternal-and-fetal-
evaluation-and-immediate-newborn-care-robert-a-sinkin-editor-in-chief/

ebookmeta.com
1. Preface
a. How This Book Is Organized
b. Style
i. Conventions Used in This Book
c. Using Code Examples
d. O’Reilly Online Learning
e. How to Contact Us
f. Acknowledgments
2. 1. Introduction
3. 2. TypeScript: A 10_000 Foot View

a. The Compiler
b. The Type System
i. TypeScript Versus JavaScript

c. Code Editor Setup


i. tsconfig.json
ii. tslint.json
d. index.ts
e. Exercises

4. 3. All About Types


a. Talking About Types
b. The ABCs of Types
i. any
ii. unknown
iii. boolean
iv. number
v. bigint
vi. string
vii. symbol
viii. Objects
ix. Intermission: Type Aliases, Unions,
and Intersections
x. Arrays
xi. Tuples
xii. null, undefined, void, and never
xiii. Enums
c. Summary
d. Exercises
5. 4. Functions
a. Declaring and Invoking Functions

i. Optional and Default Parameters


ii. Rest Parameters
iii. call, apply, and bind
iv. Typing this
v. Generator Functions
vi. Iterators
vii. Call Signatures
viii. Contextual Typing
ix. Overloaded Function Types
b. Polymorphism
i. When Are Generics Bound?
ii. Where Can You Declare Generics?
iii. Generic Type Inference
iv. Generic Type Aliases
v. Bounded Polymorphism
vi. Generic Type Defaults

c. Type-Driven Development
d. Summary
e. Exercises
6. 5. Classes and Interfaces

a. Classes and Inheritance


b. super
c. Using this as a Return Type
d. Interfaces

i. Declaration Merging
ii. Implementations
iii. Implementing Interfaces Versus
Extending Abstract Classes
e. Classes Are Structurally Typed
f. Classes Declare Both Values and Types
g. Polymorphism
h. Mixins
i. Decorators
j. Simulating final Classes
k. Design Patterns

i. Factory Pattern
ii. Builder Pattern
l. Summary
m. Exercises
7. 6. Advanced Types

a. Relationships Between Types


i. Subtypes and Supertypes
ii. Variance
iii. Assignability
iv. Type Widening
v. Refinement
b. Totality
c. Advanced Object Types

i. Type Operators for Object Types


ii. The Record Type
iii. Mapped Types
iv. Companion Object Pattern
d. Advanced Function Types
i. Improving Type Inference for Tuples
ii. User-Defined Type Guards

e. Conditional Types
i. Distributive Conditionals
ii. The infer Keyword
iii. Built-in Conditional Types

f. Escape Hatches
i. Type Assertions
ii. Nonnull Assertions
iii. Definite Assignment Assertions

g. Simulating Nominal Types


h. Safely Extending the Prototype
i. Summary
j. Exercises
8. 7. Handling Errors
a. Returning null
b. Throwing Exceptions
c. Returning Exceptions
d. The Option Type
e. Summary
f. Exercises
9. 8. Asynchronous Programming, Concurrency, and
Parallelism
a. JavaScript’s Event Loop
b. Working with Callbacks
c. Regaining Sanity with Promises
d. async and await
e. Async Streams
i. Event Emitters
f. Typesafe Multithreading

i. In the Browser: With Web Workers


ii. In NodeJS: With Child Processes
g. Summary
h. Exercises
10. 9. Frontend and Backend Frameworks
a. Frontend Frameworks

i. React
ii. Angular 6/7
b. Typesafe APIs
c. Backend Frameworks
d. Summary
11. 10. Namespaces.Modules

a. A Brief History of JavaScript Modules


b. import, export
i. Dynamic Imports
ii. Using CommonJS and AMD Code
iii. Module Mode Versus Script Mode
c. Namespaces

i. Collisions
ii. Compiled Output

d. Declaration Merging
e. Summary
f. Exercise
12. 11. Interoperating with JavaScript

a. Type Declarations

i. Ambient Variable Declarations


ii. Ambient Type Declarations
iii. Ambient Module Declarations

b. Gradually Migrating from JavaScript to


TypeScript

i. Step 1: Add TSC


ii. Step 2a: Enable Typechecking for
JavaScript (Optional)
iii. Step 2b: Add JSDoc Annotations
(Optional)
iv. Step 3: Rename Your Files to .ts
v. Step 4: Make It strict
c. Type Lookup for JavaScript
d. Using Third-Party JavaScript

i. JavaScript That Comes with Type


Declarations
ii. JavaScript That Has Type Declarations
on DefinitelyTyped
iii. JavaScript That Doesn’t Have Type
Declarations on DefinitelyTyped

e. Summary
13. 12. Building and Running TypeScript

a. Building Your TypeScript Project


i. Project Layout
ii. Artifacts
iii. Dialing In Your Compile Target
iv. Enabling Source Maps
v. Project References
vi. Error Monitoring

b. Running TypeScript on the Server


c. Running TypeScript in the Browser
d. Publishing Your TypeScript Code to NPM
e. Triple-Slash Directives

i. The types Directive


ii. The amd-module Directive
f. Summary
14. 13. Conclusion
15. A. Type Operators
16. B. Type Utilities
17. C. Scoped Declarations
a. Does It Generate a Type?
b. Does It Merge?

18. D. Recipes for Writing Declaration Files for Third-


Party JavaScript Modules
a. Types of Exports

i. Globals
ii. ES2015 Exports
iii. CommonJS Exports
iv. UMD Exports

b. Extending a Module

i. Globals
ii. Modules
19. E. Triple-Slash Directives

a. Internal Directives
b. Deprecated Directives
20. F. TSC Compiler Flags for Safety
21. G. TSX
22. Index
Programming TypeScript
Making Your JavaScript Applications Scale

Boris Cherny
Programming TypeScript

by Boris Cherny

Copyright © 2019 Boris Cherny. All rights reserved.

Printed in the United States of America.

Published by O’Reilly Media, Inc., 1005 Gravenstein Highway


North, Sebastopol, CA 95472.

O’Reilly books may be purchased for educational, business, or


sales promotional use. Online editions are also available for
most titles (http://oreilly.com). For more information, contact
our corporate/institutional sales department: 800-998-9938 or
[email protected].
Development Editor: Angela Rufino Indexer: Margaret Troutman

Acquisitions Editor: Jennifer


Interior Designer: David Futato
Pollock

Cover Designer: Karen


Production Editor: Katherine Tozer
Montgomery

Copyeditor: Rachel Head Illustrator: Rebecca Demarest

Proofreader: Charles Roumeliotis

May 2019: First Edition

Revision History for the First Edition


2019-04-18: First Release

See http://oreilly.com/catalog/errata.csp?isbn=9781492037651
for release details.

The O’Reilly logo is a registered trademark of O’Reilly Media,


Inc. Programming TypeScript, the cover image, and related
trade dress are trademarks of O’Reilly Media, Inc.
The views expressed in this work are those of the author, and
do not represent the publisher’s views. While the publisher and
the author have used good faith efforts to ensure that the
information and instructions contained in this work are
accurate, the publisher and the author disclaim all
responsibility for errors or omissions, including without
limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and
instructions contained in this work is at your own risk. If any
code samples or other technology this work contains or
describes is subject to open source licenses or the intellectual
property rights of others, it is your responsibility to ensure that
your use thereof complies with such licenses and/or rights.

978-1-492-03765-1

[LSI]
Dedication

To Sasha and Michael, who might also fall in love with types,
someday.
Preface
This is a book for programmers of all walks: professional
JavaScript engineers, C# people, Java sympathizers, Python
lovers, Ruby aficionados, Haskell nerds. Whatever language(s)
you write in, so long as you have some experience
programming and know the basics of functions, variables,
classes, and errors, this book is for you. Some experience with
JavaScript, including a basic knowledge of the Document
Object Model (DOM) and the network, will help you along the
way—while we don’t dive deep into these concepts, they are a
wellspring of excellent examples, and if you’re not familiar with
them the examples might not make as much sense.

Regardless of what programming languages you’ve used in the


past, what unites all of us is our shared experience of tracking
down exceptions, tracing through code line by line to figure out
what went wrong and how we can fix it. This is the experience
that TypeScript helps prevent by examining your code
automatically and pointing out the mistakes you may have
missed.

It’s OK if you haven’t worked with a statically typed language


before. I’ll teach you about types and how to use them
effectively to make your programs crash less, document your
code better, and scale your applications across more users,
engineers, and servers. I’ll try to avoid big words when I can,
and explain ideas in a way that’s intuitive, memorable, and
practical, using lots of examples along the way to help keep
things concrete.

That’s the thing about TypeScript: unlike a lot of other typed


languages, TypeScript is intensely practical. It invents
completely new concepts so you can speak more concisely and
precisely, letting you write applications in a way that’s fun,
modern, and safe.
How This Book Is Organized
This book has two aims: to give you a deep understanding of
how the TypeScript language works (theory) and provide
bucketfuls of pragmatic advice about how to write production
TypeScript code (practice).

Because TypeScript is such a practical language, theory quickly


turns to practice, and most of this book ends up being a mix of
the two, with the first couple of chapters almost entirely
theory, and the last few almost completely practice.

I’ll start with the basics of what compilers, typecheckers, and


types are. I’ll then give a broad overview of the different types
and type operators in TypeScript, what they’re for, and how
you use them. Using what we’ve learned, I’ll cover some
advanced topics like TypeScript’s most sophisticated type
system features, error handling, and asynchronous
programming. Finally, I’ll wrap up with how to use TypeScript
with your favorite frameworks (frontend and backend),
migrating your existing JavaScript project to TypeScript, and
running your TypeScript application in production.

Most chapters come with a set of exercises at the end. Try to


do these yourself—they’ll give you a deeper intuition for what
we cover than just reading would. Answers for chapter
exercises are available online, at
https://github.com/bcherny/programming-typescript-answers.
Style
Throughout this book, I tried to stick to a single code style.
Some aspects of this style are deeply personal—for example:

I only use semicolons when necessary.

I indent with two spaces.

I use short variable names like a, f, or _ where the


program is a quick snippet, or where the structure of
the program is more important than the details.

Some aspects of the code style, however, are things that I


think you should do too. A few of these are:

You should use the latest JavaScript syntax and


features (the latest JavaScript version is usually just
called “esnext”). This will keep your code in line with
the latest standards, improving interoperability and
Googleability, and it can help reduce ramp-up time for
new hires. It also lets you take advantage of powerful,
modern JavaScript features like arrow functions,
promises, and generators.

You should keep your data structures immutable with


spreads (...) most of the time.1

You should make sure everything has a type, inferred


when possible. Be careful not to abuse explicit types;
this will help keep your code clear and terse, and
improve safety by surfacing incorrect types rather than
bandaiding over them.

You should keep your code reusable and generic.


Polymorphism (see “Polymorphism”) is your best
friend.

Of course, these ideas are hardly new. But TypeScript works


especially well when you stick to them. TypeScript’s built-in
downlevel compiler, support for read-only types, powerful type
inference, deep support for polymorphism, and completely
structural type system encourage good coding style, while the
language remains incredibly expressive and true to the
underlying JavaScript.

A couple more notes before we begin.

JavaScript doesn’t expose pointers and references; instead it


has value and reference types. Values are immutable, and
include things like strings, numbers, and booleans, while
references point to often-mutable data structures like arrays,
objects, and functions. When I use the word “value” in this
book, I usually mean it loosely to refer to either a JavaScript
value or a reference.

Lastly, you might find yourself writing less-than-ideal


TypeScript code in the wild when interoperating with
JavaScript, or incorrectly typed third-party libraries, or legacy
code, or if you’re in a rush. This book largely presents how you
should write TypeScript, and makes an argument for why you
should try really hard not to make compromises. But in
practice, how correct your code is is up to you and your team.

Conventions Used in This Book


The following typographical conventions are used in this book:

Italic

Indicates new terms, URLs, email addresses, filenames, and


file extensions.

Constant width

Used for program listings, as well as within paragraphs to


refer to program elements such as variable or function
names, data types, environment variables, statements, and
keywords.

Constant width italic

Shows text that should be replaced with user-supplied


values or by values determined by context.

TIP
This element signifies a tip or suggestion.
NOTE
This element signifies a general note.

WARNING
This element indicates a warning or caution.

Using Code Examples


Supplemental material (code examples, exercises, etc.) is
available for download at
https://github.com/bcherny/programming-typescript-answers.

This book is here to help you get your job done. In general, if
example code is offered with this book, you may use it in your
programs and documentation. You do not need to contact us
for permission unless you’re reproducing a significant portion
of the code. For example, writing a program that uses several
chunks of code from this book does not require permission.
Selling or distributing a CD-ROM of examples from O’Reilly
books does require permission. Answering a question by citing
this book and quoting example code does not require
permission. Incorporating a significant amount of example
code from this book into your product’s documentation does
require permission.
We appreciate, but do not require, attribution. An attribution
usually includes the title, author, publisher, and ISBN. For
example: “Programming TypeScript by Boris Cherny (O’Reilly).
Copyright 2019 Boris Cherny, 978-1-492-03765-1.”

If you feel your use of code examples falls outside fair use or
the permission given above, feel free to contact us at
[email protected].

O’Reilly Online Learning

NOTE
For almost 40 years, O’Reilly Media has provided technology and business
training, knowledge, and insight to help companies succeed.

Our unique network of experts and innovators share their


knowledge and expertise through books, articles, conferences,
and our online learning platform. O’Reilly’s online learning
platform gives you on-demand access to live training courses,
in-depth learning paths, interactive coding environments, and a
vast collection of text and video from O’Reilly and 200+ other
publishers. For more information, please visit
http://oreilly.com.
How to Contact Us
Please address comments and questions concerning this book
to the publisher:

O’Reilly Media, Inc.

1005 Gravenstein Highway North

Sebastopol, CA 95472

800-998-9938 (in the United States or Canada)

707-829-0515 (international or local)

707-829-0104 (fax)

We have a web page for this book, where we list errata,


examples, and any additional information. You can access this
page at https://oreil.ly/programming-typescript.

To comment or ask technical questions about this book, send


email to [email protected].

For more information about our books, courses, conferences,


and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia


Acknowledgments
This book is the product of years’ worth of snippets and
doodles, followed by a year’s worth of early mornings and
nights and weekends and holidays spent writing.

Thank you to O’Rielly for the opportunity to work on this book,


and to my editor Angela Rufino for the support throughout the
process. Thank you to Nick Nance for his contribution in
“Typesafe APIs”, and to Shyam Seshadri for his contribution in
“Angular 6/7”. Thanks to my technical editors: Daniel
Rosenwasser of the TypeScript team, who spent an
unreasonable amount of time reading through this manuscript
and guiding me through the nuances of TypeScript’s type
system, and Jonathan Creamer, Yakov Fain, and Paul Buying,
and Rachel Head for technical edits and feedback. Thanks to
my family—Liza and Ilya, Vadim, Roza and Alik, Faina and Yosif
—for encouraging me to pursue this project.

Most of all, thanks to my partner Sara Gilford, who supported


me throughout the writing process, even when it meant calling
off weekend plans, late nights writing and coding, and far too
many unprompted conversations about the ins and outs of
type systems. I couldn’t have done it without you, and I’m
forever grateful for your support.

1 If you’re not coming from JavaScript, here’s an example: if you have


an object o, and you want to add a property k to it with the value 3,
you can either mutate o directly—o.k = 3—or you can apply your
change to o, creating a new object as a result—let p = {...o,
k: 3}.
Chapter 1. Introduction
So, you decided to buy a book about TypeScript. Why?

Maybe it’s because you’re sick of those weird cannot read


property blah of undefined JavaScript errors. Or maybe
you heard TypeScript can help your code scale better, and
wanted to see what all the fuss is about. Or you’re a C#
person, and have been thinking of trying out this whole
JavaScript thing. Or you’re a functional programmer, and
decided it was time to take your chops to the next level. Or
your boss was so fed up with your code causing production
issues that they gave you this book as a Christmas present
(stop me if I’m getting warm).

Whatever your reasons are, what you’ve heard is true.


TypeScript is the language that will power the next generation
of web apps, mobile apps, NodeJS projects, and Internet of
Things (IoT) devices. It will make your programs safer by
checking for common mistakes, serve as documentation for
yourself and future engineers, make refactoring painless, and
make, like, half of your unit tests unnecessary (“What unit
tests?”). TypeScript will double your productivity as a
programmer, and it will land you a date with that cute barista
across the street.
But before you go rushing across the street, let’s unpack all of
that a little bit, starting with this: what exactly do I mean when
I say “safer”? What I am talking about, of course, is type
safety.

TYPE SAFETY
Using types to prevent programs from doing invalid things.1

Here are a few examples of things that are invalid:

Multiplying a number and a list

Calling a function with a list of strings when it actually


needs a list of objects

Calling a method on an object when that method


doesn’t actually exist on that object

Importing a module that was recently moved

There are some programming languages that try to make the


most of mistakes like these. They try to figure out what you
really meant when you did something invalid, because hey, you
do what you can, right? Take JavaScript, for example:

3 + [] // Evaluates to the string "3"

let obj = {}
obj.foo // Evaluates to undefined
function a(b) {
return b/2
}
a("z") // Evaluates to NaN

Notice that instead of throwing exceptions when you try to do


things that are obviously invalid, JavaScript tries to make the
best of it and avoids exceptions whenever it can. Is JavaScript
being helpful? Certainly. Does it make it easier for you to catch
bugs quickly? Probably not.

Now imagine if JavaScript threw more exceptions instead of


quietly making the best of what we gave it. We might get
feedback like this instead:

3 + [] // Error: Did you really mean to ad

let obj = {}
obj.foo // Error: You forgot to define the

function a(b) {
return b/2
}
a("z") // Error: The function "a" expects
// but you gave it a string.

Don’t get me wrong: trying to fix our mistakes for us is a neat


feature for a programming language to have (if only it worked
for more than just programs!). But for JavaScript, this feature
creates a disconnect between when you make a mistake in
your code, and when you find out that you made a mistake in
your code. Often, that means that the first time you hear about
your mistake will be from someone else.

So here’s a question: when exactly does JavaScript tell you


that you made a mistake?

Right: when you actually run your program. Your program


might get run when you test it in a browser, or when a user
visits your website, or when you run a unit test. If you’re
disciplined and write plenty of unit tests and end-to-end tests,
smoke test your code before pushing it, and test it internally
for a while before shipping it to users, you will hopefully find
out about your error before your users do. But what if you
don’t?

That’s where TypeScript comes in. Even cooler than the fact
that TypeScript gives you helpful error messages is when it
gives them to you: TypeScript gives you error messages in
your text editor, as you type. That means you don’t have to
rely on unit tests or smoke tests or coworkers to catch these
sorts of issues: TypeScript will catch them for you and warn
you about them as you write your program. Let’s see what
TypeScript says about our previous example:

3 + [] // Error TS2365: Operator '+' canno


// and 'never[]'.
let obj = {}
obj.foo // Error TS2339: Property 'foo' doe

function a(b: number) {


return b / 2
}
a("z") // Error TS2345: Argument of type '
// parameter of type 'number'.

In addition to eliminating entire classes of type-related bugs,


this will actually change the way you write code. You will find
yourself sketching out a program at the type level before you
fill it in at the value level;2 you will think about edge cases as
you design your program, not as an afterthought; and you will
design programs that are simpler, faster, easier to understand,
and easier to maintain.

Are you ready to begin the journey? Let’s go!

1 Depending on which statically typed language you use, “invalid” can


mean a range of things, from programs that will crash when you run
them to things that won’t crash but are clearly nonsensical.

2 If you’re not sure what “type level” means here, don’t worry. We’ll go
over it in depth in later chapters.
Chapter 2. TypeScript: A
10_000 Foot View
Over the next few chapters, I’ll introduce the TypeScript
language, give you an overview of how the TypeScript
Compiler (TSC) works, and take you on a tour of TypeScript’s
features and the patterns you can develop with them. We’ll
start with the compiler.

The Compiler
Depending on what programming languages you worked with
in the past (that is, before you decided to buy this book and
commit to a life of type safety), you’ll have a different
understanding of how programs work. The way TypeScript
works is unusual compared to other mainstream languages like
JavaScript or Java, so it’s important that we’re on the same
page before we go any further.

Let’s start broad: programs are files that contain a bunch of


text written by you, the programmer. That text is parsed by a
special program called a compiler, which transforms it into an
abstract syntax tree (AST), a data structure that ignores things
like whitespace, comments, and where you stand on the tabs
versus spaces debate. The compiler then converts that AST to
a lower-level representation called bytecode. You can feed that
bytecode into another program called a runtime to evaluate it
and get a result. So when you run a program, what you’re
really doing is telling the runtime to evaluate the bytecode
generated by the compiler from the AST parsed from your
source code. The details vary, but for most languages this is an
accurate high-level view.

Once again, the steps are:

1. Program is parsed into an AST.

2. AST is compiled to bytecode.

3. Bytecode is evaluated by the runtime.

Where TypeScript is special is that instead of compiling straight


to bytecode, TypeScript compiles to… JavaScript code! You
then run that JavaScript code like you normally would—in your
browser, or with NodeJS, or by hand with a paper and pen (for
anyone reading this after the machine uprising has begun).

At this point you may be thinking: “Wait! In the last chapter


you said TypeScript makes my code safer! When does that
happen?”

Great question. I actually skipped over a crucial step: after the


TypeScript Compiler generates an AST for your program—but
before it emits code—it typechecks your code.
TYPECHECKER
A special program that verifies that your code is typesafe.

This typechecking is the magic behind TypeScript. It’s how


TypeScript makes sure that your program works as you expect,
that there aren’t obvious mistakes, and that the cute barista
across the street really will call you back when they said they
would. (Don’t worry, they’re probably just busy.)

So if we include typechecking and JavaScript emission, the


process of compiling TypeScript now looks roughly like
Figure 2-1:

Figure 2-1. Compiling and running TypeScript


Steps 1–3 are done by TSC, and steps 4–6 are done by the
JavaScript runtime that lives in your browser, NodeJS, or
whatever JavaScript engine you’re using.

NOTE
JavaScript compilers and runtimes tend to be smushed into a single
program called an engine; as a programmer, this is what you’ll normally
interact with. It’s how V8 (the engine powering NodeJS, Chrome, and
Opera), SpiderMonkey (Firefox), JSCore (Safari), and Chakra (Edge)
work, and it’s what gives JavaScript the appearance of being an
interpreted language.

In this process, steps 1–2 use your program’s types; step 3


does not. That’s worth reiterating: when TSC compiles your
code from TypeScript to JavaScript, it won’t look at your types.
That means your program’s types will never affect your
program’s generated output, and are only used for
typechecking. This feature makes it foolproof to play around
with, update, and improve your program’s types, without
risking breaking your application.

The Type System


Modern languages have all sorts of different type systems.
TYPE SYSTEM
A set of rules that a typechecker uses to assign types to your program.

There are generally two kinds of type systems: type systems in


which you have to tell the compiler what type everything is
with explicit syntax, and type systems that infer the types of
things for you automatically. Both approaches have trade-offs.1

TypeScript is inspired by both kinds of type systems: you can


explicitly annotate your types, or you can let TypeScript infer
most of them for you.

To explicitly signal to TypeScript what your types are, use


annotations. Annotations take the form value: type and tell the
typechecker, “Hey! You see this value here? Its type is type.”
Let’s look at a few examples (the comments following each line
are the actual types inferred by TypeScript):

let a: number = 1 // a is a number


let b: string = 'hello' // b is a string
let c: boolean[] = [true, false] // c is an array of

And if you want TypeScript to infer your types for you, just
leave them off and let TypeScript get to work:

let a = 1 // a is a number
let b = 'hello' // b is a string
let c = [true, false] // c is an array of

Right away, you’ll notice how good TypeScript is at inferring


types for you. If you leave off the annotations, the types are
the same! Throughout this book, we will use annotations only
when necessary, and let TypeScript work its inference magic
for us whenever possible.

NOTE
In general, it is good style to let TypeScript infer as many types as it can
for you, keeping explicitly typed code to a minimum.

TypeScript Versus JavaScript


Let’s take a deeper look at TypeScript’s type system, and how
it compares to JavaScript’s type system. Table 2-1 presents an
overview. A good understanding of the differences is key to
building a mental model of how TypeScript works.
Table 2-1. Comparing JavaScript’s and TypeScript’s type
systems

Type system feature JavaScript TypeScript

How are types bound? Dynamically Statically

Are types automatically


Yes No (mostly)
converted?

When are types checked? At runtime At compile time

At runtime At compile time


When are errors surfaced?
(mostly) (mostly)

HOW ARE TYPES BOUND?

Dynamic type binding means that JavaScript needs to actually


run your program to know the types of things in it. JavaScript
doesn’t know your types before running your program.

TypeScript is a gradually typed language. That means that


TypeScript works best when it knows the types of everything in
your program at compile time, but it doesn’t have to know
every type in order to compile your program. Even in an
untyped program TypeScript can infer some types for you and
catch some mistakes, but without knowing the types for
everything, it will let a lot of mistakes slip through to your
users.

This gradual typing is really useful for migrating legacy


codebases from untyped JavaScript to typed TypeScript (more
on that in “Gradually Migrating from JavaScript to TypeScript”),
but unless you’re in the middle of migrating your codebase,
you should aim for 100% type coverage. That is the approach
this book takes, except where explicitly noted.

ARE TYPES AUTOMATICALLY CONVERTED?

JavaScript is weakly typed, meaning if you do something


invalid like add a number and an array (like we did in
Chapter 1), it will apply a bunch of rules to figure out what you
really meant so it can do the best it can with what you gave it.
Let’s walk through the specific example of how JavaScript
evaluates 3 + [1]:

1. JavaScript notices that 3 is a number and [1] is an


array.

2. Because we’re using +, it assumes we want to


concatenate the two.

3. It implicitly converts 3 to a string, yielding "3".

4. It implicitly converts [1] to a string, yielding "1".

5. It concatenates the results, yielding "31".


Other documents randomly have
different content
GENERAL REGULATIONS.
Each deputy, when not occupied in the performance of his own special
duties, is to render such assistance to the clerk and to his associate deputies
as may be in his power, or as the pressure of duties in a particular
department may render necessary.

The deputies are expected to notify the clerk of any interference by


members or others with their duties, and of all improper approaches or
requests made to them by any person. They are not to exhibit to any person
any bill or other document in their possession without leave of the clerk.

Perfect courtesy must at all times be maintained towards members,


reporters, associate deputies, and all who have business to transact with the
department; but interference with legislation cannot be allowed under any
circumstances.

To Members, Officers and Reporters—It is especially requested that no


member, officer or reporter will interrupt the assistant clerk while engaged in
keeping the journal. “No journal, record, account or paper,” of any kind may
be taken from the desk, unless by express permission of the clerk.

Sergeant-at-Arms—This officer is the executive officer of the House. He has


charge of the chambers and appurtenant conveniences of the House. He
controls the police regulations, attends to the warming of the chambers,
serves the subpœnas and warrants of the House, announces messages from
the Governor and from the Senate, provides rooms for committees, receives
from the Secretary of State all public documents ordered or coming in due
course, and distributes the same through the post-office, or otherwise, to
members and officers entitled thereto. He is to organize his department with
such system that each of his subordinates shall know his precise duties, and
he is to see that each performs his duty promptly, thoroughly and
courteously. He is required to keep the chamber open from 8 o’clock A. M. to
10 o’clock P. M.

He should have the printed bills and other documents in his possession so
classified and arranged that he can at once answer any call upon him for
them.
His assistant assists him generally in the discharge of his duties, and takes
his place when he is absent.

The Door Keeper attends to the principal door; opens and closes it for the
entry and exit of all persons; maintains order in the lobby and vestibule;
sees that visitors are seated, and that the regulations of the House, in his
department, are strictly enforced.

The Assistant Door Keepers, each at their respective stations, are to


discharge the same duties as the principal door keeper. They must be in
attendance as well during the recess as the sessions of the House to keep
out intruders and maintain order.

The Firemen attend to the warming and ventilation of the House chamber,
and under the direction of the sergeant-at-arms, make themselves generally
useful.

The door keepers and firemen are responsible to the sergeant-at-arms.

DUTIES OF MESSENGERS.
To be in attendance from 8 o’clock A. M. until 10 o’clock P. M. every day
(Sundays excepted), whether the House is in session or not.

To receive the journals and printed bills from the Sergeant-at-Arms, and
arrange them in order on the file of each member.

Not to leave the House chamber during the morning hour, or absent
themselves from the sessions of the House during an entire day, except
upon leave of the Speaker or the House.

During the morning hour to take the positions assigned to them by the
Clerk; and, standing up, so as to see and be seen, hold themselves in
readiness to bring all bills, resolutions, etc., from the several members to the
Clerk, when presented.

After the expiration of the morning hour, when not engaged in filing bills,
etc., for the members they have in charge, to answer promptly any call, and
render assistance to any member requiring it.
To refrain from throwing any paper balls, darts, or other missile; to move
lightly across the House chamber, and demean themselves respectfully
towards every member and officer of the House.

STATIONERY.
The Secretary of State furnishes to the Sergeant-at-Arms the stationery
required by the members, the clerk and other officers.

NEWSPAPERS.
In regard to the supply of newspapers there are no regulations. The House
determines what papers, and how many, shall be furnished.

PROCESS OF PASSING BILLS.


Some diversity of practice exists herein, but the ordinary method in the
House is as follows:

A member having prepared a bill and endorsed the title thereof, together
with his name, upon the back of it, rises to his feet, at such time as the
introduction of bills is in order, and says:

“Mr. Speaker.”

If recognized, the Speaker responds:

“The gentleman from ——.”

The member announces:

“I ask leave to introduce a bill.”

The bill is then sent to the Clerk by a messenger. The Clerk then reads the
title of the bill, and places it on file for its first reading, and when the order
for the first reading of bills is reached, the Clerk reads the first bill on file at
length, when the Speaker announces:

“First reading of the bill.”

The second reading of bills must be on a day subsequent to their first


reading. When the Speaker calls for the second reading of bills, the Clerk
reads the first bill on file for second reading at length, when the Speaker
announces:

“Second reading of the bill.”

The bill is then usually referred to such standing committee, or select


committee, or to the general file for Committee of the Whole, as the House
may determine.

If the bill has been referred to a standing committee, or select committee, it


is in due course reported back to the House by the committee, when it is
placed in the general file.

Bills in the general file are usually considered in Committee of the Whole in
the exact order in which they are placed upon the file. Proceedings in
Committee of the Whole will be elsewhere considered.

After a Committee of the Whole has completed its action upon any bill, and
reported the same back to the House, and any recommendations made by
the committee passed upon, it is taken up in its order, when the Speaker
puts the following question:

“Shall this bill be engrossed, and read a third time?”

If decided affirmatively the bill is thereby referred to the engrossing


committee. Upon its return engrossed from the engrossing clerk, the original
and engrossed bills are placed in the hands of the Committee on Engrossed
Bills, who compare them and correct any errors which they may find. When
found correct, or made so, the committee report them to the House as
correctly engrossed, when the original is filed by the Clerk, and the
engrossed bill goes into the order of “bills ready for a third reading.”

When, under the order of business, the bill is reached, the title of the bill is
read, and the bill itself is read at length, when the Speaker says as follows:
“This bill having been read three several times, the question is: Shall the bill
pass?”

If the bill passes it is taken to the Senate, with a message announcing its
passage by the House, and asking the concurrence of the Senate therein.

Going through with a similar process in the Senate, it is returned with a


message announcing their action upon it.

If the Senate concurs, the bill is sent to the Enrolling Clerk, who makes a
copy thereof, as is elsewhere described. When enrolled, it goes to the
Committee on Enrolled Bills, who compare it with the engrossed bill. When
found or made correct, they report the bill to the House as correctly
enrolled; the engrossed bill is filed by the Clerk; the enrolled bill is then
endorsed by the Clerk as having originated in the House (for the information
of the Governor, in case he vetoes it). It is then referred to a joint committee
of enrollment, who present the same to the Speaker, who has the title of the
bill read in hearing of the House, and then signs it, after which the joint
committee present the bill to the President of the Senate, who has the title
of the bill read in hearing of the Senate, and then signs it. The committee
then proceed to the Governor and present the bill thus duly signed for his
approval, and report that fact to the House, and the hour when it was
deposited in the Governor’s hands. The Governor, if he approves the bill,
informs the House in which it originated of that fact, and that he has
deposited it with the Secretary of State.

This is the ordinary process of a bill through all its stages until it becomes a
law. A bill of great interest or importance, or one which is warmly contested,
may, by reason of majority and minority reports, special orders,
recommitment, amendments, substitutes, committees of conference, and
various other parliamentary appliances, pass through a vast number of
stages not before enumerated.

Senate bills coming into the House after passing the Senate, are read twice
by title and then read at length, and then referred to the appropriate
committee.

After consideration in Committee of the Whole, the recommendation of the


committee is acted upon in the House, the question being, after
recommendations are disposed of:
“Shall this bill be ordered to a third reading?”

If it is decided affirmatively, the bill passes into the order of “bills on third
reading;” and when reached in that order, the question is:

“Shall this bill be concurred in?”

If concurred in, the bill is returned to the Senate, with the message
informing it of that fact.

COMMITTEE OF THE WHOLE.


The Committee of the Whole is an expedient to simplify the business of
legislative bodies. No record is made of its proceedings, and it has no
officers except of its own creation, for temporary purposes. It is liable to
instant dissolution in case of disorder, when the Speaker takes the chair for a
Call of the House, or an adjournment, and in case of a message from the
Senate or Governor, when the Speaker takes the chair to receive it.

The House may resolve itself into a Committee of the Whole upon some
particular bill, resolution or subject, or it may go into Committee of the
Whole upon the general file of bills.

In the first case the motion is:

“That the House do now resolve itself into a Committee of the Whole upon
[bill No. ——, A, a bill ——], or [joint resolution No. ----, A, providing, etc.],
or [upon all bills relating to ——], as the case may be.”

In the second case it is:

“That the House do now resolve itself into a Committee of the Whole upon
the general file of bills.”

Bills, resolutions, and general matters which have been once considered in
committee of the whole, and in which progress has been made, and leave
granted for further consideration, have the preference. The motion of the
Committee of the Whole, for their further consideration, must be made
under the head of “bills in which the committee of the whole have made
progress and obtained leave to sit again;” and in which case the member
who presided when the same matter was previously considered in
committee of the whole, resumes the chair.

The motion for the committee of the whole upon the general file, must be
made under the order of “bills not yet considered in committee of the
whole.”

When the House resolves itself into committee of the whole, the Speaker
selects a chairman as follows:

“The gentleman from ——, Mr ——, will take the chair.”

The appointed chairman advances to the Speaker’s desk, and having taken
the chair, receives from the clerk the papers indicated by the motion for the
committee, when the chairman announces:

“Gentlemen,—The committee have under consideration bill No. ——, entitled


——” (reading the title from the back of the bill). Or in case of consideration
of the general file: “The committee have under consideration the general file
of bills; the first in order is bill No. ——, A, entitled ——. The first section is
as follows.”

The chairman then reads the first section, and asks:

“Are there any amendments proposed to the first section?”

If none are offered, the chairman says:

“No amendments being offered to the first section, the second section will
be read.”

This process is continued through the whole bill, when at the close of the
reading the chairman says:

“The ——th section and the whole bill have now been read, and are open to
amendment.”

At this point, after the friends of the bill have perfected it, it is customary for
the opponents of the bill to open their attack. After the discussion of the bill
to such an extent as may be desired, if no amendments are made, the final
vote is generally upon a motion—
“That the bill be reported back to the House without amendment.”

If any other bills are before the committee, they are proceeded with in the
same manner. If it is desired to have further consideration of any matter
before the committee, or if the general file has not been gone through with,
the motion is:

“That the committee rise, report progress, and ask leave to sit again.”

If the committee has completed its duties, the motion is:

“That the committee rise and report.”

Which being analagous to a motion to adjourn, is not debatable. The


chairman states the matter as follows:

“It is moved that the committee do now rise and report (or otherwise, as the
case may be).”

“Is the committee ready for the question?”

“Gentlemen,—Those who are of opinion that this committee do now rise and
report, say ‘Aye;’ those of a contrary opinion say ‘No.’”

In case of doubt a division must be had, as the ayes and noes cannot be
called in committee of the whole.

When the committee rises, the Speaker resumes his seat, and the chairman,
in his place on the floor, reports as follows:

“Mr. Speaker.”

The Speaker answers:

“Mr. Chairman.”

Who reports:

“The committee of the whole have had under consideration bill No. ——, A,
entitled ——, and have instructed me to report the same to the House with
amendment” (or as the case may be).
When the general file has been under consideration, the report is as follows:

“The committee of the whole have had under consideration the general file
of bills, have gone through the same, and have directed me to report to the
House the bills contained therein, with sundry amendments and
recommendations as follows, to-wit:” [Here follows the titles of bills
considered, with action taken upon them.]

In case the file has been left unfinished, the report is:

“The committee of the whole have had under consideration the general file
of bills, and have made some progress therein. I am directed to report back
the following bills, with the amendments and recommendations hereinafter
specified, and ask leave for the committee to sit again.” [Here follows the
report of amendments, etc., as above.]

In the latter report the question is:

“Shall leave be granted?”

When, upon a count, it is ascertained that a quorum is not present, the


report is:

“The committee of the whole have had under consideration ——, and, after
some progress therein, find there is no quorum present; that fact I herewith
report to you.”

In case of confusion or disorder, the Speaker, of his own accord, resumes the
chair temporarily and without any formality, for the purpose of suppressing
it. When order is restored the chairman resumes the chair, and the business
proceeds.

Upon the coming in of a report, the recommendations are usually at once


acted on by the House.

When, in committee of the whole, any member desires to offer an


amendment, it must be reduced to writing and sent to the chairman, who
reads it, and asks:

“Is the committee ready for the question upon the amendment?”
And if no further amendment or debate offer, he puts the question in the
usual manner.

After a section is once passed, with an unsuccessful effort to amend it, no


further amendments are in order. The strictness of this rule is, however, not
always adhered to; an amendment once made may, however, be
reconsidered. Such a motion is:

“That the amendment offered by the gentleman from ——, to the ----th
section, be reconsidered.”

And is stated as follows:

“The gentleman from —— moves that the amendment of the gentleman


from —— to the ——th section be reconsidered.”

“Is the committee ready for the question?”

“Those who are of the opinion that said amendment be reconsidered say
‘Aye;’ those of the contrary opinion say ‘No.’”

In case the amendment is reconsidered, the Speaker says:

“The motion is carried. The amendment is reconsidered. The question now


recurs upon the adoption of the amendment. Is the committee ready for the
question?” etc.

FORMS.
Of Titles:

No. ——, a bill to ——.

Amending Bill:

A bill relating to ——, and amendatory of section ——, of chapter ----, of the
——.

Repealing Bill:
A bill to repeal section ——, of chapter ——, of the ——, relating to ——
(filling the blanks with the proper section and chapter of the revised statutes
or general laws, designating the same, and also the subject, object or
purpose of the section of the chapter repealed; and in the body of every bill,
the full title of the act repealed shall be recited at length).

Appropriation Bill:

“To appropriate to —— the sum of —— dollars.”

Titles should be written inside the bill, and endorsed upon the outside as
follows:

No. ——, A.
A Bill to change the name of
Andrew Jackson to James Madison.
Mr. Gorden.

Resolutions should not be entitled, but should have the name of the mover
endorsed upon them. The same rule applies to amendments.

Resolutions are of no special form; the following may serve as a general


guide in such matters:

Res. No. ——, A.

“Resolved,—That three thousand copies of the Governor’s message be


furnished by the printer to the Sergeant-at-Arms, for the use of the House.

“Mr. Tucker.”

For reports the following form is used:

“The committee on ——, to which was referred bill No. ——, A., a bill to ——,
respectfully report the same back to the House with an amendment, and
recommend its passage when amended;” or, “and recommend that it do
pass;” or, “and recommend that it be indefinitely postponed;” or, “and
recommend that it be referred to the delegation from ——;” or, “to a select
committee.”
Or, if the committee report by bill:

“The committee on ——, to which was referred ——, respectfully report “by
bill No. ——, A., a bill to ——;

“And recommend its passage.”

An enacting clause must precede the body of the bill.

It must invariably be in the following form:

Be it enacted by the General Assembly of the State of Colorado: Const., Art.


5, Sec. 18.

INVESTIGATIONS.
When an investigation is required into any matter, the person most
interested in having the inquiry made, should move the appointment of a
committee to take the subject in charge. This is done by resolution. The
resolution should be so drawn as to state the precise subject to be
investigated, and to give the committee all the power which the mover may
deem necessary to a thorough examination into the subject matter to be laid
before them; this should be done to prevent any misapprehension as to the
intention and extent of the inquiry to be made. In case of the adoption of
the resolution, the mover, together with other members, will be appointed a
committee. They have power to send for persons and papers. The form of a
subpœna is as follows:

“The State of Colorado, }

“To —— ——: You are hereby commanded, that, laying aside all business
and excuse, you personally appear and attend before Messrs. —— ——, on
the part of the Senate, and Messrs. —— ——, on the part of the House, a
joint committee appointed under a resolution of the Senate and House, to
investigate at the room of said committee ——, in the city of Denver, the
capital of the State, on the —— day of ——-, A. D. one thousand eight
hundred and ——, at the hour of —— in the —— noon, then and there, and
from time to time, as required by said committee, to testify and give
evidence upon the matters of inquiry before said committee.
“Hereof fail not, under penalty in such case made and provided.

“Given at the House chamber, in the city of Denver aforesaid, this —— day
of ——, A. D. 18——.

“—— ——, Speaker of the House.

“Attest: —— ——, Chief Clerk of the House.”

In case of a refusal to appear, or a refusal to testify, the following form of


certificate has been used:

“To Hon. —— ——, Speaker of the House:

“I, —— ——, chairman of the joint committee appointed to investigate ----,


do hereby certify that —— has been duly subpœnaed to appear before said
committee, as will fully appear by the writ served, and affidavit of service
accompanying the same, on file with the chief clerk of the House.

“I further certify that said —— —— has failed to appear before said


committee, according to the exigency or mandate of said writ or subpœna.

“Dated Denver, ——, 18——, at —— o’clock.

—— ——.”

Upon which a warrant, in the following form, may be used:

“The State of Colorado to the Sergeant-at-Arms of the House:

“It appearing that a writ of subpœna, directed to —— ——, commanding


him to personally appear and attend before Messrs. —— ----, on the part of
the Senate, and Messrs. —— ——, on the part of the House, a joint
committee appointed under a resolution of the Senate and House, to
investigate —— ——, at the room of said committee, in the city of Denver,
the capital of the State, the —— day of ----, A. D. 18——, at the hour of ——
in the —— noon, then and there, and from time to time, as required by said
committee, to testify and give evidence upon the matter of inquiry before
said committee, has been issued, and that the said writ of subpœna was
duly and personally served upon the said —— ——, on the day of ——, A. D.
18——, and returned; and it further appearing by the certificate of the
chairman of the said joint committee, that the said —— —— has failed or
neglected to appear before the said committee in obedience to the mandate
of the said subpœna: therefore, you are hereby commanded, the name of
the State of Colorado, to take the body of him, the said —— ——, and bring
him before the House, so that he may testify and give evidence before the
said committee, and answer for his contempt of the House in not obeying
the mandate of said subpœna. Hereof fail not.

“Given at the House chamber, in the city of Denver aforesaid, this —— day
of ——, A. D. 18——.

“—— ——, Speaker of the House.

“—— ——, Chief Clerk of House.”

To which the return, in ordinary cases, would be:

“By virtue of the within process, I did, on the —— day of ——, 18—, arrest
the body of —— ——, and took him before the committee within named,
and the said —— —— having refused to answer interrogatories propounded
by said committee, I have him, by direction of said committee, now before
the House.

“House Chamber, ——, 18—.

“—— ——, Sergeant-at-Arms of the House.”

A resolution, declaring the defaulter to be in contempt, is the next


proceeding.

The following is a form for such resolution:

“Resolved, That the neglect or failure of —— —— to appear before the joint


investigating committee, composed of Messrs. —— ----, of the Senate, and
Messrs. —— ——, of the House, in compliance with the mandate of the writ
of subpœna of this House, served upon him on the —— instant, as fully
appears by the said writ and affidavit of the service thereof endorsed
thereon, now on file with the Chief Clerk of this House, be and the said
neglect and failure is hereby declared a contempt of this House.”

This is followed by an interrogatory, as follows:


“Int. 1.—Why did you not appear before the joint investigating committee,
as required by the mandate of the subpœna served upon you the ——
instant?”

To which the defaulter pleads before judgment is inflicted.

Another form is as follows:

“Resolved, That the refusal of —— —— to answer the questions put to him


by a member of the joint investigating committee, on the ---- instant, and
which questions were certified to the House by ---- ——, chairman of said
committee; and are now in writing, on file with the Chief Clerk of the House,
be, and the same is hereby declared a contempt of this House.”

Followed by the corresponding interrogatory:

“Why did you not answer the question put or propounded to you on the ——
instant, by a member of the joint investigating committee, of which —— ——
is chairman?”

In case the answer is satisfactory, the offender is discharged; if otherwise,


he is punished by reprimand, fine or imprisonment, or both; but such
imprisonment cannot extend beyond the session of the Legislature.

The report of a Committee on Investigation should consist of three parts:

1. The testimony taken.

2. A statement of the facts proven thereby, or conclusions derived


therefrom.

3. Resolutions, or a bill providing for the action which the committee deem
proper to be taken in the premises.

QUORUMS.
Whole number electable:
“Not less than 25 nor more than 49.”
To expel a member:
“Two-thirds.”
To do any business except to adjourn from day to day, and compel the
attendance of absent members:
“A majority.”
To cause the ayes and nays on any question to be entered upon the journal:
“Two members.”
To pass any bill which imposes, continues or renews a tax, or creates a debt
or charge, or makes, continues or renews any appropriation of public trust,
money or release, discharges or commutes a claim or demand from the
State:
“A majority of all.”
To adjourn from day to day:
“A smaller number than a majority.”
To agree to an amendment of the Constitution:
“A majority of all the members.”
To recommend a constitutional convention:
“Two-thirds of all.”
To contract a public debt:
“A majority of all members elect.”
To pass any resolution or motion:
“A majority of all present.”
To pass any bill:
“A majority of all the members elect.”
To make a Call of the House:
“Two members.”
To order the previous question:
“A majority present.”
To suspend the rules:
“Two-thirds of the members present.”
To change the order of business:
“Two-thirds of the members present.”
To bring in a bill which has been rejected by the Senate:
“Two-thirds of the House.”
To agree to an amendment made by the Senate to a House bill bill with an
emergency clause:
“Two-thirds of all members elect.”
RULES AND ORDERS OF THE SENATE.
1. The hours of meeting shall be 10 A. M. and 2 P. M., unless otherwise ordered.

2. The President having taken the chair, and a quorum being present, the journal of the preceding
day shall be read, to the end that any mistake may be corrected, which shall be made in the
entries. A quorum shall consist of a majority of the members of the Senate.

3. No member shall speak to another, or otherwise interrupt the business of the Senate, or read
any newspaper, while the journal or public papers are being read, or when any member is
speaking in debate. No smoking shall be allowed during the sitting of the Senate.

4. Every member, previous to speaking, shall rise from his chair, and respectfully address the
President, and shall confine himself to the question under debate, and avoid personality.

5. No member shall speak more than twice on any one debate on the same day, without leave of
the Senate.

6. When two members rise at the same time, the President shall name the person to speak; but
in all cases the member who shall first rise and address the chair shall speak first.

7. When a member shall be called to order by the President or a Senator, he shall sit down; and
every question of order shall be decided by the President, without debate, subject to an appeal to
the Senate; and the President may call for the sense of the Senate on any question of order.

8. If the member be called to order by a Senator for words spoken, the exceptional words shall
immediately be taken down in writing by the Secretary, that the President may be better enabled
to judge of the matter.

9. No member shall absent himself from the service of the Senate without leave of the Senate,
and in case a less number than a quorum of the Senate shall convene, they, or a majority of
them, may send the Sergeant-at-Arms, or other suitable person or persons, for any or all absent
members, at the expense of such absent members respectively, unless such excuse for non-
attendance shall be made, as the Senate, when a quorum is convened, shall judge sufficient.

10. No motion shall be debated until the same shall be seconded.

11. When a motion shall be made and seconded, it shall be reduced to writing, if desired by the
President or any member, delivered at the table of the Secretary, and read before the same shall
be debated.

12. When a question is under debate no motion shall be received, except as otherwise provided in
these rules, but to adjourn, to lie on the table, to postpone indefinitely, to postpone to a day
certain, to commit, or amend, which several motions shall have precedence in the order they
stand arranged. Any motion may be withdrawn by the mover at any time before a discussion,
amendment, or ordering of the yeas and nays, except a motion to reconsider, which shall not be
withdrawn without leave of the Senate. A motion to adjourn shall always be in order. That, and
the motion to lay on the table, shall be decided without debate.

13. The previous question shall be in this form: “Shall the main question be now put?” It shall
only be entertained when demanded by a majority of the members present, and its effects shall
be to put an end to all debate, and bring the Senate to a direct vote upon amendments reported
by a committee, if any, upon pending amendments, and then upon the main question. On a
motion for the previous question, and prior to the seconding of the same, a call of the Senate
shall be in order, but after a majority shall have seconded such motion, no call shall be in order
prior to a decision of the main question.

14. When the previous question is decided in the negative, it shall leave the main question under
debate for the residue of the sitting, unless disposed of by taking the question, or in some other
manner.

15. Any five members may make a call of the Senate and require absent members to be sent for,
but a call of the Senate cannot be made after the voting has commenced, and the call of the
Senate being in order, and the absentees noted, the doors shall be closed and no member
permitted to leave the room until the report of the Sergeant-at-Arms be received and acted upon,
or further proceedings in the call be suspended by a vote of two-thirds of the Senate.

16. The President shall rise to put a question, but may state it sitting.

17. No motion or proposition on a subject different from that under consideration shall be
admitted under color of amendment.

18. If a question in debate contains several points, any member may have the same divided, but
on motion to strike out and insert, it shall not be in order to move for a division of the question,
but the rejection of a motion to strike out and insert one proposition shall not prevent a motion to
strike out and insert a different proposition, nor prevent a subsequent motion simply to strike out,
nor shall the rejection of a motion simply to strike out, prevent a subsequent motion to strike out
and insert.

19. All so called substitute motions and resolutions shall be considered as amendments only, and
shall be subject to the rules relating thereto, except such matters as may be reported by
committees.

20. In filling up blanks the largest sum and longest time shall be first put.

21. When the reading of a paper is called for, and the same is objected to by any member, it shall
be determined by a vote of the Senate, and without debate.

22. When the ayes and nays shall be called for by two of the members present, each member
called upon shall declare openly, and without debate, his assent or dissent to the question, unless
by special reason he be excused by the Senate.

23. When the ayes and nays shall be taken on any question in pursuance of the above rule, no
member shall be permitted, under any circumstances whatever, to vote after the decision is
announced from the chair.

24. On a motion made and seconded to shut the doors of the Senate, on the discussion of any
business which may in the opinion of the Senate require secrecy, the presiding officer shall direct
the lobby to be cleared, and during the discussion of such motion the doors shall remain shut.

25. No motion shall be deemed in order to admit any person or persons whatsoever, other than a
Senator, within the Senate chamber, to present any petition, memorial or address.

26. When a question has been carried or negatived, it shall be in order for any member of the
majority to move for the reconsideration thereof. But no motion for the reconsideration of any
vote shall be in order after a bill, resolution, message, report, amendment, or motion, upon which
the vote was taken, shall have gone out of the possession of the Senate, announcing their
decision; nor shall any motion to reconsider be in order unless made on the same day on which
the vote was taken, or within the next two days of actual session of the Senate thereafter.

27. The President of the Senate, or President pro tempore, shall have the right to name a
member to perform the duties of the Chair; but such substitution shall be for that day only.

28. Every petition or memorial, or other paper, shall be referred, of course, without putting a
question for that purpose, unless the reference be objected to at the time the same is presented;
and before any petition or other paper shall be received or read, a brief statement of the contents
of the same shall be verbally made by the introducer.

29. The following shall be the order of business for the day:

1. Calling the roll.


2. Prayer by the Chaplain.
3. Reading the journal.
4. Petitions and memorials.
5. Reports from standing committees.
6. Reports of special or select committees.
7. Resolutions.
8. Amendments proposed by the House to Senate bills.
9. Introduction of bills.
10. Bills on first reading.
11. Bills on second reading.
12. Bills on third reading, and final passage.
13. Special order of the day.
14. Unfinished business.

30. All bills introduced in the Senate shall, after the second reading be printed for the use of the
members, but no other paper or document shall be printed without special order.

31. Every bill shall receive three readings at length previous to its being passed, and the President
shall give notice at each, whether it be the first, second or third, which readings shall be on three
different days. All resolutions to which the signature of the Governor may be requisite, shall be
treated, in all respects, in the introduction and form of proceedings on them in the Senate, in a
similar manner with bills, and all other resolutions shall lie on the table one day before being
taken up for consideration, and also all reports of committees.
32. No bill shall be committed or amended until it shall have been twice read, after which it shall
be referred to a committee.

33. All bills after second reading shall be printed and considered by the Senate in the committee
of the whole before they shall be taken up and proceeded on by the Senate, agreeably to the
standing rules, unless otherwise ordered. When the Senate shall consider a bill or resolution as a
committee of the whole, the President or President pro tempore shall call a member to fill the
chair during the time the Senate shall remain in committee of the whole.

34. The final question, upon the second reading of every bill, resolution or motion, originating in
the Senate and requiring three readings previous to being passed, shall be, “whether it shall be
engrossed and read a third time?” And no amendments shall be received for discussion at a third
reading, of any bill, resolution or motion, unless by unanimous consent of the members present,
but it shall at all times be in order, upon the final passage of any bill, resolution or motion, to
move its commitment, and shall such commitment take place, and any amendment be reported
by the committee, said bill, resolution or motion, shall again be read the second time and
considered in committee of the whole, and then the aforesaid question shall be again put.

35. The title of bills shall be inserted on the journals.

36. When motions are made for reference of the same subject to a select committee and to a
standing committee, the question on reference to the standing committee shall first be put.

37. When motions are made for reference of the same subject to a select committee and to a
standing committee, the question on reference to the standing committee shall first be put.

37. When nominations shall be made in writing by the Governor to the Senate, a future day shall
be assigned, unless the Senate otherwise direct, for taking them into consideration.

38. All confidential communications made by the Governor shall be kept secret. When acting on
confidential or executive business, the Senate room shall be closed to all persons except the
Secretaries and Sergeant-at-Arms. All information or remarks touching the character or
qualifications of any person nominated by the Governor to office, shall be kept secret. The
legislative proceedings, the executive proceedings, and the confidential legislative proceedings of
the Senate, shall be kept in separate and distinct books.

39. The proceedings of the Senate, when not acting in committee of the whole, shall be entered
on the journal as concisely as possible, care being taken to detail a true and accurate account of
the proceedings and every vote of the Senate shall be entered on the journal, and a brief
statement of the contents of each petition, memorial or paper presented to the Senate, shall be
inserted on the journal.

40. Messages shall be sent to the House by the Secretary or Assistant Secretary; the Secretary
having previously endorsed the final determination of the Senate thereon.

41. The Sergeant-at-Arms shall not permit any person not a member or officer of the Senate to
pass inside the railing, in the rear of the seats of the members, at any time during the session of
the Senate, except the Judges of the Supreme and District Courts, the Governor and other State
officers, and duly accredited representatives of the press, and the members of the Legislature of
the State of Colorado, and such other persons as may be invited by the members.

You might also like