【TypeScript】ts 学习之路二 —— 类型

一、变量定义

// 1、String,Number,Boolean, null, undefined
let name: string = '毛叔叔';
let age: number = 18;
let isHandsome: boolean = true;
let n: null = null;
let u: undefined

// 2、Array
let numArr: number[] = [1,2,3];
let strArr: Array<string> = ['1', '2', '3'];

// 3、any
let a: any = 1; // any 可以复制任何值

二、函数

// 参数检查
function isHamdsome (name: string) {
    console.log(name + ' so handsome');
};

isHandsome(123);
// Argument of type 'number' is not assignable to parameter of type 'string'.(类型为'数字'的参数不能分配给类型为'字符串'的参数)

// ----
// 定义函数

function oops (isHandsome: (name: string) => void) {
    isHandsome('毛叔叔')
}

oops(isHandsome);
// "毛叔叔 so handsome"


// -----

// 返回检查

function isHamdsome (name: string): Boolean {
    console.log(name + '超靓仔');
    return true;
};

isHamdsome('毛叔叔'); // true
// '毛叔叔超靓仔'
// 函数属性
type DescribableFunction = {
  description: string;
  (someArg: number): boolean; // 注意函数的定义返回值是用 :而不是 =>
};
function doSomething(fn: DescribableFunction) {
  console.log(fn.description + " returned " + fn(6));
}

const fn = (a: number) => a > 10;

fn.description = 'Jerry';


doSomething(fn)

三、对象

function introduction (person: { name: string; age: number; sex?: string }) {
    console.log('我名字叫' + person.name);
    console.log('我今年' + person.age);
    person.sex ? console.log('是个' + person?.sex + '人') : null;
}

introduction({name: '毛叔叔', age: 18});
// '我名字叫毛叔叔'
// '我今年18'

introduction({name: '毛叔叔', age: 18, sex: '男'});
// '我名字叫毛叔叔'
// '我今年18'
// '是个男人'

四、联合类型

// 如果需要对传入参数进行特殊操作,是希望能够做好判断避免出错

function printId(id: number | string) {
    console.log(id.toUpperCase());
    // Property 'toUpperCase' does not exist on type 'string | number'.(属性'toUpperCase'在类型'string | number'上不存在。)
    // Property 'toUpperCase' does not exist on type 'number'.(属性'toUpperCase'在类型' number'上不存在。)
}

// ---

// 如果该特殊操作在两个类型都可以实行的话,则无需判断

function getFirstThree(x: number[] | string) {
  return x.slice(0, 3);
}

五、字面类型

let sex: 'male' | 'female' = 'male';
console.log(sex);  //"male"

let age: 18 = 1;
console.log(age); // 1
// Type '1' is not assignable to type '18'.(类型“1”不能分配给类型“18”)

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值