We continue to publish a series of adapted and supplemented translations " TypeScript
. "
Other parts:
Primitives: string
, number
andboolean
In the JS
commonly used 3 primitive : string
, number
and boolean
. Each of them has a corresponding type in TS
:
string
, ,'Hello World'
number
, ,42
.JS
( ), ,int
float
—number
boolean
— :true
false
: String
, Number
Boolean
( ) , , , . string
, number
boolean
.
[1, 2, 3]
number[]
; (, string[]
— ..). Array<number>
, . , , (generics).
: [number]
— , (tuple).
any
TS
any
, :
let obj: any = { x: 0 } // // `any` // `any` , , `TS` obj.foo() obj() obj.bar = 100 obj = 'hello' const n: number = obj
any
, , .
noImplicitAny
TS
, any
.
, , any
. noImplicitAny
any
.
const
, let
var
:
const myName: string = 'John'
, , TS
, .. :
// - `myName` `string` const myName = 'John'
JS
, , . TS
(input), (output) .
, :
function greet(name: string) { console.log(`Hello, ${name.toUpperCase()}!`) }
:
greet(42) // Argument of type 'number' is not assignable to parameter of type 'string'. 'number' 'string'
: .
:
function getFavouriteNumber(): number { return 26 }
, TS
return
.
. , TS
, .
:
// , `TS` const names = ['Alice', 'Bob', 'John'] // names.forEach(function (s) { console.log(s.toUppercase()) // Property 'toUppercase' does not exist on type 'string'. Did you mean 'toUpperCase'? 'toUppercase' 'string'. 'toUpperCase'? }) // names.forEach((s) => { console.log(s.toUppercase()) // Property 'toUppercase' does not exist on type 'string'. Did you mean 'toUpperCase'? })
s
, TS
forEach
, s
. (contextual typing).
— . . , , :
function printCoords(pt: { x: number, y: number }) { console.log(` 'x': ${pt.x}`) console.log(` 'y': ${pt.y}`) } printCoords({ x: 3, y: 7 })
,
;
. . any
.
?
:
function printName(obj: { first: string, last?: string }) { // ... } // printName({ first: 'John' }) printName({ first: 'Jane', last: 'Air' })
JS
undefined
. , undefined
:
function printName(obj: { first: string, last?: string }) { // - , `last` console.log(obj.last.toUpperCase()) // Object is possibly 'undefined'. 'undefined' if (obj.last !== undefined) { // console.log(obj.last.toUpperCase()) } // , `JS` - (`?.`) console.log(obj.last?.toUpperCase()) }
(unions)
: , TS
, union
, , , , .
— , 2 , , . , , (members) .
, :
function printId(id: number | string) { console.log(` ID: ${id}`) } // OK printId(101) // OK printId('202') // printId({ myID: 22342 }) // Argument of type '{ myID: number }' is not assignable to parameter of type 'string | number'. Type '{ myID: number }' is not assignable to type 'number'. '{ myID: number }' 'string | number'. '{ myID: number }' 'number'
, TS
, . , string | number
, , string
:
function printId(id: number | string) { console.log(id.toUpperCase()) // Property 'toUpperCase' does not exist on type 'string | number'. Property 'toUpperCase' does not exist on type 'number'. }
(narrowing) . , TS
, string
typeof
'string'
:
function printId(id: number | string) { if (typeof id === 'string') { // `id` 'string' console.log(id.toUpperCase()) } else { // `id` 'number' console.log(id) } }
, Array.isArray
:
function welcomePeople(x: string[] | string) { if (Array.isArray(x)) { // `x` - 'string[]' console.log(', ' + x.join(' ')) } else { // `x` - 'string' console.log(' , ' + x) } }
. , , slice
. , :
function getFirstThree(x: number[] | string ) { return x.slice(0, 3) }
(type aliases)
? :
type Point = { x: number y: number } // , function printCoords(pt: Point) { console.log(` 'x': ${pt.x}`) console.log(` 'y': ${pt.y}`) } printCoords({ x: 3, y: 7 })
, , , :
type ID = number | string
: — , "" . , , TS
, :
type UserInputSanitizedString = string function sanitizeInput(str: string): UserInputSanitizedString { return sanitize(str) } // "" let userInput = sanitizeInput(getInput()) // - userInput = 'new input'
— :
interface Point { x: number y: number } function printCoords(pt: Point) { console.log(` 'x': ${pt.x}`) console.log(` 'y': ${pt.y}`) } printCoords({ x: 3, y: 7 })
TS
(structurally typed type system) — TS
, printCoords
, .. .
. interface
type
. , type
, interface
.
:
interface Animal { name: string } interface Bear extends Animal { honey: boolean } const bear = getBear() bear.name bear.honey
(intersection):
type Animal { name: string } type Bear = Animal & { honey: boolean } const bear = getBear() bear.name bear.honey
:
interface Window { title: string } interface Window { ts: TypeScriptAPI } const src = 'const a = 'Hello World'' window.ts.transpileModule(src, {})
:
type Window = { title: string } type Window = { ts: TypeScriptAPI } // : 'Window'.
: interface
, type
.
(type assertion)
, TS
.
, document.getElementById
, TS
, - HTMLElement
, , , HTMLCanvasElement
. :
const myCanvas = document.getElementById('main_canvas') as HTMLCanvasElement
( TSX-):
const myCanvas = <HTMLCanvasElement>document.getElementById('main_canvas')
TS
. , :
const x = 'hello' as number // Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. // 'string' 'number' , . , 'unknown'
. : any
( unknown
), :
const a = (expr as any) as T
(literal types)
string
number
, , .
TS
:
let changingString = 'Hello World' changingString = 'Olá Mundo' // `changingString` , // TS changingString // let changingString: string const constantString = 'Hello World' // `constantString` , // constantString // const constantString: 'Hello World'
:
let x: 'hello' = 'hello' // OK x = 'hello' // ... x = 'howdy' // Type '"howdy"' is not assignable to type '"hello"'.
, , , :
function printText(s: string, alignment: 'left' | 'right' | 'center') { // ... } printText('Hello World', 'left') printText("G'day, mate", "centre") // Argument of type '"centre"' is not assignable to parameter of type '"left" | "right" | "center"'.
:
function compare(a: string, b: string): -1 | 0 | 1 { return a === b ? 0 : a > b ? 1 : -1 }
, :
interface Options { width: number } function configure(x: Options | 'auto') { // ... } configure({ width: 100 }) configure('auto') configure('automatic') // Argument of type '"automatic"' is not assignable to parameter of type 'Options | "auto"'.
, TS
, . , :
const obj = { counter: 0 } if (someCondition) { obj.counter = 1 }
TS
1
, 0
, . , TS
, obj.counter
number
, 0
.
:
const req = { url: 'https://example.com', method: 'GET' } handleRequest(req.url, req.method) // Argument of type 'string' is not assignable to parameter of type '"GET" | "POST"'.
req.method
string
, 'GET'
. req
handleRequest
, req.method
, , GUESS
, TS
, .
2 .
- :
// 1 const req = { url: 'https://example.com', method: 'GET' as 'GET' } // 2 handleRequest(req.url, req.method as 'GET')
-
as const
:
const req = { url: 'https://example.com', method: 'GET' } as const handleRequest(req.url, req.method)
null
undefined
JS
, : null
undefined
. TS
. , , strictNullChecks
(. 1).
(non-null assertion operator)
TS
null
undefined
. !
, , .. null
undefined
:
function liveDangerously(x?: number | undefined) { // console.log(x!.toFixed()) }
(enums)
, . .
bigint
BigInt
:
// `bigint` `BigInt` const oneHundred: bigint = BigInt(100) // `bigint` const anotherHundred: bigint = 100n
symbol
Symbol()
:
const firstName = Symbol('name') const secondName = Symbol('name') if (firstName === secondName) { // This condition will always return 'false' since the types 'typeof firstName' and 'typeof secondName' have no overlap. // `firstName` `lastName` }
10% !