machao07 / interview-questions

前端技术栈相关面试知识点( Vue、React、Typescript、JavaScript...),喜欢请点start

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TypeScript基础类型

machao07 opened this issue · comments

1、给变量后面定义类型

只能是定义的类型,否则ts会提醒报错
any 可以追加其他类型

let myname: string = "achao"
let age: number = 13
let alias: any = "yaoyao"
let man: boolean = true

2、给方法、参数定义类型

  • 方法后面定义的类型时必须return返回对应类型
  • void 表示没有返回值
// 不需要返回值
function test ():void {
    return "" // 提醒报错
}

image

// 给参数定义string类型
function test (name: string):string{
    return "success"
}
test(123) // 提醒报错,参数只能是string

image

3、自定义类型

class Person {
    name: string;
    age: number;
}
let achao:Person = new Person()
achao.name = 123 // 提醒报错,只能是string
interface imagesInfoDTO {
    foler: string;
    fullName: string,
    name: string, 
    path: string,
    [key: string]: any // 动态添加对象属性
}

const imagesInfo:imagesInfoDTO = {
    foler: '',
    fullName: '',
    name: '', 
    path: '',
};

imagesInfo[str] = {
    foler: foler,
    fullName: imgFullName,
    name: imgName, 
    path: imgPath
}

4、字符串字面量类型、数字字面量类型、布尔字面量类型

interface Config {
    size: 'small' | 'big';
    isEnable:  true | false;
    margin: 0 | 2 | 4;
}

5、函数参数默认值

  • 默认参数必须放置最后,否则报错
  • 有默认参数值时,调用可不传参数
function fn(a:string, b:string, c:string = 'mo'){
  console.log(a)
  console.log(b)
  console.log(c)
}
fn("x", "y", "z")  // x y z
fn("x", "y",) // x y mo

6、函数可选参数

  • 可选参数必须在必选参数后面,否则报错
  • 可以在默认参数的后面
function fn1(a:string, b?:string, c:string = 'mo'){
  console.log(a)
  console.log(b)
  console.log(c)
}
fn1("aaaa")  // aaaa undefined mo