TypeScript是JavaScript的超集,为JavaScript 添加了可选的类型、类和模块系统。它可以编译成普通的JavaScript代码。 TypeScript支持任意浏览器,任意环境,任意系统并且是开源的。
TypeScript
BASIC TYPES
1 | > let n: number = 2 |
OPERATORS
1 | > 4 / '2' |
JAVASCRIPT BUILTINS
1 | > const n: number = (123).toString() |
INFERENCE
1 | > let n = 2 + 2 |
FUNCTIONS
1 | > function numToString(x: number): string { |
ARRAYS
1 | > let strings: string[] = ['a', 2] |
TYPE KEYWORD
1 | > type MyStringType = string |
SYNTAX ERRORS VS TYPE ERRORS
1 | > 1 &+@ 2 |
OBJECT TYPES
1 | > type User = { |
RETURN TYPE INFERENCE
1 | > function two() { |
TYPE UNIONS
1 | > function isNumber(arg: number | string): boolean { |
LITERAL TYPES
1 | > let one: 1 = 1 |
CONDITIONAL NARROWING
1 | > function add1IfNumber(n: number | boolean) { |
TUPLES
1 | > let numberAndString: [number, string] = [1, 'a'] |
LITERAL OBJECT TYPES
1 | > function extractEmail(hasEmail: {email: string}): string { |
GENERIC ARRAYS
1 | > let numbers: number[] = [1] |
OBJECT NARROWING
1 | > type HasName = {name: string} |
NULLABILITY
1 | > let numberMaybe: number | undefined |
GENERIC FUNCTIONS
1 | > function first<T>(elements: Array<T>): T { |
FUNCTION TYPES
1 | > function add1(n: number): number { |
ANY
1 | > const n: any = 5 |
DISCRIMINATED UNIONS
1 | > type StartedCourse = { |
LOGICAL OPERATOR NARROWING
1 | > function arrayLength(strings: string[] | undefined): number | undefined { |
TYPE INTERSECTIONS
1 | > type HasEmail = {email: string} |
FUNCTIONS AS ARGUMENTS
1 | > type TakesNumberReturnsNumber = (x: number) => number |
ERROR HANDLING WITH UNIONS
1 | > type ConversionSucceeded = { |
UNKNOWN
1 | > const n: unknown = 5 |
VOID
1 | > function f() { |
UNDEFINED IN ARRAYS
1 | > let strings: string[] = [] |
GENERIC OBJECT TYPES
1 | > type Pants<T1, T2> = { |
GENERIC FUNCTION TYPES
1 | > function first<T>(elements: Array<T>): T { |
TYPE PREDICATES
1 | > function isString(s: unknown): s is string { |
INDEX SIGNATURES
1 | > const strings: {[index: number]: string} = ['a', 'b', 'c'] |
GENERIC FUNCTION INFERENCE
1 | > function length<T>(elements: T[]): number { |
SHARED FIELDS
1 | > type HasEmail = {email: string} |
OPTIONAL CHAINING
1 | > type User = {name: string} |
NULLISH COALESCING
1 | > null ?? 1 |
ASSERTION FUNCTIONS
1 | > function assert(condition: boolean): asserts condition { |
NEVER
1 | > function throws(): never { |
RECURSIVE TYPES
1 | > type NestedNumberArray = number | NestedNumberArray[] |
Regex
LITERALS
1 | > /a/ |
WILDCARD
1 | > /./ |
BOUNDARIES
1 | > /^/ |
REPETITION
1 | > /a+/ |
OR
1 | > /a|b/ |
PARENS
1 | > /^(a|b)+$/ |
ESCAPING
1 | > /\+/ |
BASIC CHARACTER SETS
1 | > /[ab]/ |
BASIC CHARACTER CLASSES
1 | > /\s/ |
CHARACTER CLASSES
1 | > /\w/ |
CHARACTER SETS
1 | > /[$]/ |
MAYBE
1 | > /a?/ |
CONSTRAINED REPETITION
1 | > /a{3}/ |
WORD BOUNDARIES
1 | > /\b/ |
HEX CODES
1 | > /\xhh/ |
CHARACTER CLASSES IN SETS
1 | > /[\s-]/ |