ts is essentially a language based on js, so its syntax is similar to js.
Install typescript on mac sudo npm i typescript -g
to view the installed version tsc -v
. Solve the problem of conflict between ts and js. tsc --init
Automatically compile tsc --watch
and issue errors Strict mode tsc --noEmitOnError **显示申明**
function greeet(person: string, date: Date) {
console.log(`${
person}-${
date}.`)
}
greet('Xiaoqian', new Date())**隐士申明**
function greeet(person: any, date: any) {
console.log(`${
person}-${
date}.`)
}
greeet('小芊', new Date()) `
downgrade compile tscconfig.json' modify attribute targetrt: "es5"
strict mode
tscconfig.json'修改属性 strict: true,noImplicitAny:true,strictNullChecks:true
strict: true :类型验证
array definition`
let arr: number[] = [1, 2, 3] let arrs: Array = [1, 2, 3]
在这里插入代码片
`
Function definition retutn definition
function getnumber():number{
return 23
}。 参数定义
function getnumber():number{
return 23
}
object definition
function getnumbers(obj:{
x:number,y:string}):number{
return 23
}
getnumbers({
x:1,
y:'11'
})
union type
obj:{
x:number,y:string | number}。y:string[]. : 表示字符串数组
define an alias
type point ={
x:number,y:string | number}
function printcoor({
pt:point}){
} printcoor({
pt:1})
interface (another way to define an object type by an interface)
interface can be defined repeatedly and superimposed.
interface animal {
name:string
}
interface bear extends animal {
number:1
}
const obj:bear={
name:'',
number:1
}
type type extension
type cannot be defined repeatedly and an error will be reported
type point ={
x:number,y:string | number} &{
z:string
}
function printcoor(obj:point){
}
printcoor({
x:1,y:2,z:''})
Type assertion is defined as an unclear type instead of any, which loses the meaning of ts
const x = ('hello' as unknown)
text type
person: ‘1’
non-null assertion (determining it's not a problem with that type)
console.log(x!.toFixed())
enumerate
enum Direction {
up = 1,
a,
b
}
bigint 非常大的整数。symbol 全局唯一引用
const number:bigint = 100n
Type narrowing using if statement