一、interface接口
接口用来定义对象类型或者函数类型,类类型等等, 并且可以设置属性只读, 属性可选等操作
基本用法:
interface A {
readonly username: string;
age?: number;
sex: string;
}
const a: A = {
username: "",
age: 12,
sex: "na",
};
interface接口和type别名的区别
1.interface 只能是对象类型,type可以赋值为基本类型
2.interface具备合并能力,例如写两次interface A 会将这两次写的对象属性合并成一个。type不支持合并
3.接口具备继承能力 interface A extends B{}
4.type具备映射类型 interface 不支持
二、字面量类型和 keyof
type A = 1 | 2 | 3;
const a: A = 2;
type ROLES = "user" | "admin" | "superadmin";
const role: ROLES = "superadmin";
interface C{
user: string
age: number
}
const c: keyof C = 'user' //只能是interface C中的key('user'|'age')
三、类型保护和自定义类型保护
function foo(n: string | number) {
if (typeof n === "string") {
n.length;
}
}
function foo1(n: { username: string } | { age: number }) {
if ("username" in n) {
n.username;
}
}
class A {
username = "xiaoming";
}
class B {
age = "xiaoming";
}
function b(n: A | B) {
if (n instanceof A) {
n.username;
}
}
function c(n: "user" | 1) {
if (n === "user") {
n.length;
}
}
四、泛型
指在定义函数、接口或者类时未指定其参数类型,只有在运行时传入才能确定
type A<T> = T; // 泛型
type B<T = string> = T; // 泛型默认值
type C<T, U> = T | U; // 多泛型
let a: A<string> = "hello";
let a1: A<number> = 1;
let b: B = "1";
let b1: B<number> = 1;
let c: C<number, boolean> = 1;
c = false;
type MyArray<T> = T[];
let d: MyArray<number> = [1, 2, 3];
//函数
function foo<T>(n: T){
}
foo<string>('')
foo(1) // 不写泛型参数ts会自动推断
// 函数和接口结合
interface A<T> {
(n?: T): void;
default?: T;
}
let foo: A<string> = () => {
console.log(1);
};
foo();
foo.default = "1";
let foo1: A<number> = () => {
console.log(1);
};
foo1.default = 1;
foo1(123);
// 类
class Foo<T>{
username!: T
}
const f = new Foo<string>()
f.username = 'a'
class Baz extends Foo<number>{
}
const f1 = new Baz()
f1.username = 1
// 泛型约束
//泛型约束
type A ={
length: number
}
function ft<T extends A>(n: T){
}
ft({length:1})
ft<string>('hello')
五、映射类型与内置工具类型
可以将已知类型的每个属性都变为可选的或者只读的(只能用别名实现)
常用内置工具类型
六、类中使用类型
interface A<T> {
username: T
age: number
showName(n: T): T
}
class Foo implements A<string> {
username: string = 'xiaoming'
age: number = 20
gender: string = 'male'
showName = (n: string): string => {
return n
}
}