typescript 关键字
typescript内置关键字及其用法
类型推断相关
- extends
- typeof
- keyof
- instanceof
- is
- as
- infer
- new
extends
A extends B 表明类型A继承类型B,即类型A属于类型B,A相当于是B的子类型
type A = string
type B = string | number
// 成立
A extends B
// 不成立
any extends B
boolean extends B
// interface继承,多继承
interface Foo extends Bar, Zoo {
}
// 类继承
class Sub extends SuperClass {
}
typeof
获取构造值的类型,另外一个功能与js中的typeof一样,并在此基础上做了类型断言
例如枚举,class,变量
enum Shape {
polygon,
rectangle
}
typeof Shape
class Foo {
static shape = Shape.polygon
}
type FooCconstructor = typeof Foo
let FooC: FooCconstructor
FooC.shape // Shape.polygon
const config = {
foo: '',
}
// { foo: number }
typeof config
if(typeof config.foo == 'string'){
//成立时则为 string
}
keyof
获取类型的key联合类型
// 'foo' | 'bar'
type K = keyof {foo: string, bar: any}
// number | keyof string[]
type ArrKey = keyof Array<string>
instanceof
A 是否为 B 的实例,即成立时A为B类型
as
用于断言, A 一定是 B类型
不会推断/偷懒?, as any 帮你解决难题.当然有时候typescript脑子转不过来,只能用any.适当的使用any也是合理的
let cat
cat as any
// 与上相同,更推荐使用as用法,语义明确
<any>cat
// 对于一些顽固分子,不得已,请先as 两遍
// 形如
A as any as B
// as const, 断言为const常量
let dog = 'dog' as const
is
用于判断断言类型,但只能用于函数,当函数返回true时,断言成立
function isArray(arg: any): arg is any[] {
return Array.isArray(a)
}
let a = []
if(isArray(a)){
// a: any[]
}
infer
推断类型
type ArrayElement<T> = T extends Array<infer E> ? E : never
// number
ArrayElement<number[]>
// never
ArrayElement<number>
new
new 一个实例
或者表示构造一个实例类型
// 推断实例类型
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
// c表示构造原型
function create<T>(c: {new(): T; }): T {
return new c();
}
// 这样子的通常用于对非ts编写的代码做类型声明
interface Vue {
new(): VueClass
}
// VueClass
var vm = new Vue()
其他关键字
- interface
- enum
- type
- implements
- class
- private
- public
- protected
- static
- readonly
- declare
- module
- namespace
interface 与type
好似两兄弟,大多数情况下都一样,可混用
type Foo = {
bar: string
}
interface Foo {
bar: string
}
差别
除去写法上不一样,还有一下差别
interface中可使用extends关键字表示继承关系type声明的类型可以使用&,|类型符号
enum
枚举
enum Word {
a = 1 ,
// 设置第一个枚举值为数字,以下不手动设置将会自动递增
b, // 2
c // 3
}
enum Shape {
// 指定为字符串
polygon = 'polygon',
rectangle = 'rectangle'
}
public,private,protected
了解Java的同学便知道,他们用于表示Class属性和方法的访问权限的修饰词,在Class中的方法或属性上使用(不能在static静态方法或者属性上使用)
public是公开的,所有对象都能访问,无其他权限修饰符则默认为public
protected子类和自身才能访问
private只能在该类中访问
static
声明class的静态方法或者属性
class Foo {
static play(){
//
}
}
// 无需实例化即可调用
Foo.play()
readonly
让属性仅为可读
class Foo {
// readonly可与public,private,protected结合使用,两者不冲突
public readonly name = 'Mr Yangmei'
}
let f = new Foo()
// 抛错
f.name = 'zhang'
declare
声明(包括变量)类型,在通常在.d.ts声明文件中声明类型
declare const foo : {
bar: string
}
foo.bar
declare interface Foo {
}
declare class Bar {
}
declare module 'some-module' {
export interface Foo {
}
export function bar(): void
}
版权声明:本文为qq_40188710原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。