Think about your problem in the following way:
- How can I be sure that provided type has "replace()" method?
- What would happen if I provide different type e.g. number or null?
You have to somehow tell Typescript that you expect to get an argument that has method "replace()". You can do it by creating additional interface and mention that generic type extends that interface:
interface Replacable {
replace: (regexp: RegExp, str: string) => string
}
function getSomething<T extends Replacable>(value: T): any{
const temp = doSomething<T>(value);
console.log(temp);
}
function doSomething<T extends Replacable>(value: T): any {
return value.replace(/\s/g, '');
}
Read more about Generic Constraints here: https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints
return <string>value.replace()? Or(value as string).replace()