You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Tips: 干啥都可以,等同于 ES 时代的 JS,对他操作之后返回的也是 any。可以访问变量里面的任何属性或方法
3. Type Inference
> let y = 1;
undefined
> y = 'a'
⨯ Unable to compile TypeScript
[eval].ts (1,1): Type '"a"' is not assignable to type 'number'. (2322)
> let l = null
undefined
> l = 1
1
Tips: 在推导(Type Inference)出到底是哪个 Type 之前,访问变量的属性或方法的时候有限制,只能访问共有的属性或方法
5. Interfaces
>interfaceFoo{a: number,b: string,c?: boolean}undefined>let BBar: Foo={a: 1,b: 2}⨯UnabletocompileTypeScript[eval].ts(1,5): Type '{ a: number; b: number;}' is not assignable to type 'Foo'.Typesofproperty'b'areincompatible.Type'number'isnotassignabletotype'string'.(2322)>interfaceFoo{readonlya: number,b: string,c?: boolean,[propName: string]: any}
Tips:
? 表示该属性可以不存在。但总的来说都不允许添加未定义的属性。
[propName: string]: any 表示 Foo 中可以有 key 是 string, value 是 any 的任意属性,值的注意的是这里的 string 和 any必须覆盖到之前定义的确定属性和可选属性。
typespecialType='a'|'b'|'c';
let a: specialType='a'
13. Tuple
let a: [number,string]=[1,'2']
Tips: 越界只能是已知类型的联合类型;可单独修改某个一个值;
14. Enum
enumdays={ a, b, c }enumdays={ a =1.5, b, c }
15. Class
classAextendsB{publicname: string;privateage: number;protectedgrade: string;constructor(name){super(props);}}abstractclassFoo{publicname: string;constructor(name){this.name=name;}publicabstractsay()}classBarextendsFoo{publicsay(){}}
let bar: Bar=newBar()interfaceM{publicmethod1()}interfaceN{publicmethod2()}interfaceLextendsN{publicmethod3();}classBarextendsFooimplementsM,L{publicmethod1(){};publicmethod2(){};publicmethod3(){}}
Tips:
public、private、protected 和 Java 中行为一致。
Abstract Class 不能被实例化,只能被其他的 class 继承,同时 abstract 中定义的 abstract 方法必须要被继承的子类实现(implements)。
Interfaces 用于不同 class 之间共有的属性或者方法。 一个 class 可以 implements 多个 interface,interface 之间也可以继承 (承上 5.interfaces)
16. Generics
functionmethods<T>(a: number, b: T): Array<T>{}
function swapTurple<T><U>(turple: [T, U]): [U, T] {}
interface LengthGen {length: number}
function testMethod<TextendsLengthGen>(a: T): T {}
function testMethod<TextendsU>(a: T, b: U): T {} // 保证 T的属性 U 上一定也会有
interface FooInterface<T>{(a: number,value: T): Array<T>}
let foo: FooInterface<any> = function method<T>(a: number, value T): Array<T>{}
TypeScript 风靡全球后不懂 TypeScript 的前端绝对不是一个好前端。TypeScript 的设计来源于大多数的静态语言,如果曾经有静态语言的开发经验,TypeScript 一整个下午就能上手。
这里记录一下 TypeScript 常用的一些语法层面的东西,方便日后查阅。
Get Start
1. Type
boolean
,number
,string
,void
,undefined
,null
2. Any
3. Type Inference
4. Union Types
5. Interfaces
6. Array
7. Function
8. Type Assertion
9. Declare
10. Standard built-in objects
11. Type Alias
12. String Literal Types
13. Tuple
14. Enum
15. Class
16. Generics
参考资料
The text was updated successfully, but these errors were encountered: