1

What if I use a first-class function that is stored in a variable which is an unknown type. Trying to do so getting the following compiler error.

error TS2571: Object is of type 'unknown'.

    let somethingany : unknown; 
    let somethingunknown : unknown;
    const loadUnkown: unknown  = (params: unknown) : unknown=>{  <--- exactly her is the mistake
        if(typeof params == 'string'){
            return params.trim();
        }
    }
    
    
    somethingany = loadUnkown('werwq'); <----//eror here
    console.log(somethingany.trim());
    
    somethingunknown = loadUnkown('werwer');  <----//eror here
    if(typeof somethingunknown == 'string'){
        console.log(somethingunknown.trim());
    }

Though any is working precisely.

let somethingany : any;
let somethingunknown : any;
const loadString: any = (params: any): any =>{
    return params;
}

somethingany = loadString('asdasdsad');
console.log(somethingany.trim());

somethingunknown = loadString('asdasdsad');
if(typeof somethingunknown == 'string'){
    console.log(somethingunknown.trim());
}

Need to know why const loadUnkown: unknown = ()=>{} is a problem

ANIK ISLAM SHOJIB
  • 3,002
  • 1
  • 27
  • 36

1 Answers1

1

As requested here is my answer. Your question does not make a lot of sense as the the variable foo already has a type in your example (type: (params: unknown) => unknown) if you delete the unknown. But I assume that's just for the sake of demonstration.

If you define the function foo as unknown the typescript compiler does not know which type foo has.

The good thing about this is that whoever uses this variable has to do a typecheck before the typescript compiler lets him pass.

const foo: unknown = (params: unknown): unknown => {
    return null;
}
// not working -> the typescript compiler says:
// This expression is not callable.
// Type '{}' has no call signatures.
foo('werwq');

So the one using that variable has to do a typecheck first and the typescript compiler let's the user of the variable use it as function.

if (typeof foo === "function") {
    foo('werwq');
}
// or even
switch (typeof foo) {
    case "function":
        foo("a");
}
kevinSpaceyIsKeyserSöze
  • 3,693
  • 2
  • 16
  • 25