[英]What is the type of this function argument?
我如何为我的第二种方法编写类型验证(我正在努力解决参数v因为它需要从数组中的值继承它的类型
lo.foreEach = ([1,{},true],(v,i,list))=>{/** some code **/}
我必须使用 generics 吗? 我不知道该怎么做。
第二个问题使用Array <mixed>
和 Array <Any>
有什么区别
//@flow
type loObjectT = {
push: (Array<mixed>, mixed) => void,
//HERE
forEach: (Array<mixed>, (v:'****',i:number,list:Array) => void) => void,
};
const lo: loObjectT = {};
lo.push = function (target, filler) {
if (Array.isArray(target)) {
target[target.length] = filler;
}
throw new Error("i accept only 'Array'");
};
lo.forEach = function (target, callback) {
if (Array.isArray(target)) {
for (let i = 0; i < target.length; i++) {
callback(target[i], i, target);
}
}
throw new Error("i accept 'Array' & 'Set");
};
请问你能帮帮我吗?
带typescript:(注意mixed
不是TypeScript类型,和any
一样)
type loObjectT = {
push: (target: any[],filler: any) => void,
forEach: (target: any[],callback: (v:any,i:number,list: any[]) => void) => void,
};
const lo: loObjectT = {
push:function (target, filler) {
if (!Array.isArray(target)) throw new Error("i accept only 'Array'");
target.push(filler)
},
forEach: function (target, callback) {
if (!Array.isArray(target)) throw new Error("i accept 'Array' & 'Set");
for (let i = 0; i < target.length; i++) {
callback(target[i], i, target);
}
}
}
还要避免使用any
类型。 如果没有类型检查,则使用 TypeScript 毫无意义。
无论如何,我看不到过度编码的意义。 您已经拥有 javascript 的这些内置函数:
const myArray: any[] = []
// Push whatever to array
myArray.push("whatever")
myArray.push({whatever:"whatever"})
// For each position of the array run a callback
myArray.forEach((myArrayPosition,index) => {
// Your callback code
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.