1.普通interface 泛型函数定义
interface func{
(source: string, target: string): boolean;
}
let testFunc: func = function (source, target) {
return source == target;
}
interface func2<T>{
(source: T): T;
}
interface login{
username: string;
}
let testFunc2: func2<login> = function (source) {
console.log(source.username);
return source;
}
let testFunc3: func2<{name:string}> = function(source) {
console.log(source.name);
return source;
}
interface func3<T,R>{
(source: T&R): boolean;
}
type User= {
username: string;
}
type Password = {
password: string;
}
let testFunc4: func3<User,Password> = function(source) {
return (source.username === 'zengwe' && source.password === '123456');
}
2.定义索引范围
比如这样的表单验证:
let dataX = {
username: {
required: {
args: true,
msg: 'must be have'
}
},
age: {
required: {
args: false
},
isInt: {
args: true,
msg: 'must be integer'
}
}
}
我们还要复用表单
写法:
interface UserForm {
username: string,
password: string
}
interface validata {
required?,
isInt?,
len?
}
type FormValidata<t> = {
[p in keyof t]: {
[x in keyof validata]: {
args: any,
msg: string
}
}
}
let data: FormValidata<UserForm> = {
username: {
required: {
args: true,
msg: 'must be have'
}
},
password: {
isInt: {
args: true,
msg: 'ss'
}
}
};
这种是限制索引,还有不限制第二次的索引,但是索引值得类型可以限制
interface Data1{
[index: string]: {
lon: number,
lat: number
}
}
type Data2={
[index: string]: {
lon: number,
lat: number
}
}