typescript的一些奇奇怪怪的定义

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
    }    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值