php网站建设视频,天津品牌网站建设,糟糕的网站设计,网站收录作用目录
TS的常见用法介绍 example01.ts
逃避类型检查#xff1a;any
思考一下~#xff1a;不知道类型
类型标注
函数#xff08;参数和返回值#xff09;
匿名函数
TS如何知道匿名函数的类型#xff1f; TS是一种标注式语言#xff0c;不侵入JS的设计
TS的常见用法…目录
TS的常见用法介绍 example01.ts
逃避类型检查any
思考一下~不知道类型
类型标注
函数参数和返回值
匿名函数
TS如何知道匿名函数的类型 TS是一种标注式语言不侵入JS的设计
TS的常见用法介绍
文章内容
基础类型、数组any/unkown类型标注函数对象类型联合别名接口断言字面类型null and undefined枚举类型
基础类型、数组
stringnumberbooleannull【人为赋值null】undefined【就是没有设置值】Array,T代表数组中元素类型 为什么要求数组中类型统一人类思考问题的方式类型的方式思考程序如一组人
// null;undefined
const a {}
a[aaa] // undefined
a[aaa] null // null
if(a[aaa] null) {}
// js
new Array()
// TS;浏览器中不支持要有1TS环境
new ArrayT() example01.ts
// js语法
const a new Array()
// ts语法
const b new Arraystring()// 泛型定义数组每项元素只能式string
b.push(123)// b只能push字符串其他类型都会编译报错// 让typescript认为当前文件是一个模块这个文件里的变量都是局部的
export {}
逃避类型检查any
let obj:any { x: 0 };
// 后续都不会被检查
// any屏蔽了所有类型检查相当于你相信你对程序的理解式高于TS的
obj.foo();
obj();
obj.bar 100;
obj hello;
const n: number obj;
const a: {[key: string] :number} { x: 1 };
a.y 2
a.z 3
a.o 123 // 报错
思考一下~不知道类型
为什么要提供unknown?
let value: unknown;
value true; // ok
value 42; // ok
value hello; // ok
let value3:boolean value; // Error
类型标注
let myName:string Alice; // :string 标注类型为字符串
let yourName Bob; // 未明确标注类型会推到出此类型为string
函数参数和返回值
// greet : string - number (Haskell)
function greet(name: string): number {console.log(Hello, name.toUpperCase() !!);
}
greet(42) // Error ,要求string
let x: string greet(omg) // Error , x要求字符串返回值要求数字
匿名函数
const names [Alice, Bob, Erice];
// Arraystring
names.forEach(function (s) {// s: string // 类型的上下文推到 contextual mappingconsole.log(s.toUppercase());
});
names.map(value {// value: string // 类型的上下文推到 contextual mappingconst y: number value // Error
});
names.forEach((s) {console.log(s.toUppercase());
})
TS如何知道匿名函数的类型
contexture Typing技术
根据上下文Context推导类型还有什么是Context Typing
上下文是指程序间组件共享的知识可以是任何东西
class A {foo(){// this就是类A的上下文this.bar() }bar(){}
}
function foo2() { // 闭包const x 1function bar() { // 子闭包}
}