ts js 的超集
- 静态类型,即编译阶段进行类型检查
- 通过编译器,增强 js 语法能力
- 与 ECMAScript 同步发展。
Ts 语法 基础
let var1: string
const var2 = true
let var3: string | number
let arr: string[]
let x: [string, number]
x = ['Runoob', 1]
x = [1, 'Runoob']
console.log(x[0])
let varAny: any
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Blue
console.log(c)
let x: never
let y: number
x = 123
x = (() => {
throw new Error('exception')
})()
y = (() => {
throw new Error('exception')
})()
function error(message: string): never {
throw new Error(message)
}
function loop(): never {
while (true) {}
}
function greet(person: string): number {
return 233
}
function warn(): void {
const a = 0
}
function fn1(o: object) {
}
function fn2(o: { props: number }) {
}
type Prop = { props: number }
function fn3(o: Prop) { }
const someValue: any = 'this is a string'
const strLen = (someValue as string).length
let union: string | number
union = '1'
union = 1
type First = { first: number }
type Second = { second: number }
type FirstAndSecond = First & Second
function fn4(param: FirstAndSecond): FirstAndSecond {
return { first: 1, second: 2 }
}
function greeting(person: string, msg = 'abc', msg2?: string): string {
return ''
}
function watch(cb1: () => void): void
function watch(cb1: () => void, cb2: (v1: any, v2: any) => void): void
function watch(cb1: () => void, cb2?: (v1: any, v2: any) => void) {
if (cb1 && cb2) {
} else {
}
}
class Parent {
private _foo = 'foo'
protected bar = 'bar'
constructor(public tua = 'tua') {}
get foo() {
return this._foo
}
set foo(val) {
this._foo = val
}
}
class Child extends Parent {}
const p = new Parent()
const c = new Child()
interface Person {
firstName: string
lastName: string
}
function greeting1(person: Person) {
return 'Hello, ' + person.firstName + ' ' + person.lastName
}
greeting1({ firstName: 'Jane', lastName: 'User' })
interface Result<T> {
ok: 0 | 1
data: T
}
function getResult<T>(data: T): Result<T> {
return { ok: 1, data }
}
getResult<string>('hello')
getResult(1)
namespace Drawing {
export interface IShape {
draw()
}
}
namespace Drawing {
export class Circle implements IShape {
public draw() {
console.log('Circle is drawn')
}
}
}
module Module_Name {
export interface StringValidator {
isAcceptable(s: string): boolean
}
}
import shape = require('./IShape')
runoob.d.ts
declare module Module_Name {}