TypeScript语法学习

Posted 一杯清泉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TypeScript语法学习相关的知识,希望对你有一定的参考价值。

一、基本数据类型

let b: boolean;
b = true;
//b = 3 //报错
console.log(b);

let num: number;
num = 10;
//num = false; //报错
console.log(num);

let st: string;
st = '555'
st = "yyy"
console.log(st);

二、数组

//数组
let arr: number[] = [1, 2, 3, 4]
let arr2: string[] = ['1', 'o', '5']

let arr3: Array<number> = [1, 2, 3, 4]

//元组
let arr4: [string, boolean, number, boolean] = ['1', true, 8, false]

三、对象接口

interface IUser 
    name: String,
    age: number


//1、对象接口实现
let user: IUser =  name: '张三', age: 89 
console.log(user);

//2、接口继承,只读属性
interface IStudent extends IUser 
    readonly DNA: boolean //只读属性
    CET4: boolean;
    CET6?: boolean

let student: IStudent =  name: '张三', age: 30, CET4: false,DNA:false 
//student.DNA = true 不可以修改
console.log(student);

四、函数接口

interface IFunc 
    (name: string): void

//一般使用
let f: IFunc = (name: string): void => 
    console.log(name);


f('张三')

//索引类型,键值对类型
interface IIndex 
    [index: string]: string


let index: IIndex =  a: '1', b: '1' 
console.log(index);

五、类接口

interface IUser2 
    name: string
    say(age: number):void


class Student implements IUser2 
    name: string;
    say(age: number):void 
        console.log(age);
    

六、类

interface IMan 
    name: string


//普通类
class Man 
    say(): string 
        return "我是abstract"
    


class Father extends Man implements IMan 
    name: string;


//抽象类
abstract class Man2 
    say(): string 
        return "我是abstract"
    


class Father2 extends Man implements IMan 
    name: string;
 

七、函数

//1、具名函数
function say(content: string) 
    console.log(content);

//2、匿名函数
let speak1 = (content: string) => 
    console.log(content);


let speak2 = function (content: string) 
    console.log(content);


//可选参数
function say2(content?: string) 
    console.log(content);


say2("55555555")
say2()

//默认参数
function say3(content: string = '777777') 
    console.log(content);

say3()

八、泛型

//泛型参数
function say4<T>(speak: T) 
    console.log(speak);


say4<number>(1) //1
say4<string>("说话")  //说话

//泛型接口
interface IUser5 
    name: String

say4<IUser5>( name: "张三" ) // name: '张三' 

以上是关于TypeScript语法学习的主要内容,如果未能解决你的问题,请参考以下文章

TypeScript语法学习

TypeScript语法学习--基本类型

TypeScript语法学习

TypeScript语法学习

TypeScript语法学习

TypeScript语法学习--变量的声明