Home > database >  What is the type of this function argument?
What is the type of this function argument?

Time:08-21

How can i write a type validation for my second method (i m struggling with the argument v as it need's to inherit it's type from values in the Array

lo.foreEach = ([1,{},true],(v,i,list))=>{/** some code **/}

do i have to use generics ? i have no idea how to do it.

2nd question what is the difference between using Array<mixed> and 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 ?

CodePudding user response:

With typescript: (Note that mixed is not a TypeScript type and is the same as 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. There's no point of using TypeScript if there's no type checking.

Anyway I don't see the point of over-coding. You already have those built-in functions with 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
})
  • Related