[英]What is the type of this function argument?
How can i write a type validation for my second method (im struggling with the argument v as it need's to inherit it's type from values in the Array我如何为我的第二种方法编写类型验证(我正在努力解决参数v因为它需要从数组中的值继承它的类型
lo.foreEach = ([1,{},true],(v,i,list))=>{/** some code **/}
do i have to use generics?我必须使用 generics 吗? i have no idea how to do it.
我不知道该怎么做。
2nd question what is the difference between using Array <mixed>
and Array <Any>
第二个问题使用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");
};
Please can u help me?请问你能帮帮我吗?
With typescript: (Note that mixed
is not a TypeScript type and is the same as any
)带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);
}
}
}
Also avoid using any
type.还要避免使用
any
类型。 There's no point of using TypeScript if there's no type checking.如果没有类型检查,则使用 TypeScript 毫无意义。
Anyway I don't see the point of over-coding.无论如何,我看不到过度编码的意义。 You already have those built-in functions with javascript:
您已经拥有 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.