官网第一个例子是这样的。
message.toLowerCase()
message()
大家可能一眼看出来,这不就是让message小写,然后再调用message吗? 等等,既然message可以小写,那为什么会再调用呢?这就是问题所在。问题就是 你不知道你已经错了。
说说问题在哪
- 我们不能知道message是否有toLowerCase属性
- 即使有,可以调用吗,message可以调用吗?
- 它们返回什么?
这都是我们不知道的情况。
再看一段代码
function fn(x){
return x.a()
}
我们很清楚,这段代码要给定一个x上有a()的参数才能调用,但是 JavaScript 并没有以我们可以在代码运行时检查的方式显示这些信息。js只有执行了才知道会发生什么。
所以,也要像其他语言一样,在定义的时候就声明出是什么类型。
const firstName:string = "zhang"
const lastName:string = "san"
function person(f:string,l:string):string{
return `${f}${l}`
}
console.log(person(firstName,lastName))
typescript基础类型
string,number,boolean
每种类型有自己对应的方法,调用别人的方法会报错。
array 数组,数组里可以写基础类型,所以数组是这样表示的
const strs:Array<string> = ["a","b","c"]
const strs1:string[] = ["a","b","c"]
const nums:Array<number> = [1,2,3]
const nums1:number[] = [1,2,3]
const bools:Array<boolean> = [true,false,false]
const bools1:boolean[] = [true,false,false]
const mess:Array<string|number|boolean>=["a",1,true]
any类型
当你不希望typescript检查错误时,你可以使用any类型。
const a : any = "str"
const b : any = 1
const c : any = true
function
function sayName(myName:string){
console.log(myName);
}
sayName("zhangsan")
如何确定返回值呢?这里在参数括号后加冒号( :string),表示返回值是string
function sayName(myName:string):string{
return myName
}
sayName("zhangsan")
可选参数
在参数后加?,这里last可选
function printName(obj: { first: string; last?: string }) {
// ...
}
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });
联合类型 当你的参数可能是多种类型的时候
function printId(id: number | string) {
console.log("Your ID is: " + id);
}
// OK
printId(101);
// OK
printId("202");
类型别名
当我们希望多次使用同一个类型并用一个名称引用它。就可以定义一个type
type Point = {
x: number;
y: number;
};
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
你也可以这样
type ID = number | string;
所以上面的printId就可以这样
type ID = number | string;
function printId(id:ID) {
console.log("Your ID is: " + id);
}
// OK
printId(101);
// OK
printId("202");
接口
interface与type相似
interface Point {
x: number;
y: number;
}
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
类型别名和接口的区别
类型别名和接口非常相似,在很多情况下您可以在它们之间自由选择。几乎所有的特性interface都可以在 中使用type,主要区别在于不能重新打开类型来添加新属性,而接口总是可扩展的。
拓展接口
interface Animal {
name: string
}
interface Bear extends Animal {
honey: boolean
}
const bear = getBear()
bear.name
bear.honey
拓展类型
type Animal = {
name: string
}
type Bear = Animal & {
honey: boolean
}
const bear = getBear();
bear.name;
bear.honey;
添加新字段
interface Window {
title: string
}
interface Window {
ts: TypeScriptAPI
}
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});
创建后无法更改
type Window = {
title: string
}
type Window = {
ts: TypeScriptAPI
}
// Error: Duplicate identifier 'Window'.
类型断言
有时候你比typescript更清楚的类型,可以用as来断言,断言的意思就是,我敢断言它就是这个类型
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
未完待续>>>>