Is it possible in TypeScript for a function to accept any generic object, but preserve the concrete object shape in the type information?
I'm trying to create an interface like this:
interface Object {
state(): Object
}
Object.prototype.state = function () { ... }
in a way that the output of state()
preserves the concrete object shape in the type information. But if I use the code above and do:
let obj = {somekey: 1}.state()
obj
wil have a type of Object
, instead of {somekey: number}
.
This can easily be done with Arrays, because they are generalised on their members. Doing:
interface Array<T> {
state(): Array<T>
}
Array.prototype.state = function () { ... }
let arr = [1].state()
will preserve arr
's type as number[]
.
How can I do the same with Objects, please?
CodePudding user response:
I'm afraid you cannot do this with Object.prototype
, but you can surely write a function like this:
function identity<T>(input: T): T { return input; }
it will preserve all type information it can gain when you call it, for example:
// x has type { somekey: number }
const x = identity({somekey: 1});
Try it in the typescript playground
CodePudding user response:
Have you tried using a this
parameter?
interface Object {
state<T>(this: T): T
}
Object.prototype.state = function () { return this }
let obj = { somekey: 1 }.state()
// ^? { somekey: number }