#Typing `this` in Record<>

22 messages · Page 1 of 1 (latest)

near basalt
#

This is not working, I can't figure out how to type this with giving limits to the types with Record

function test<U extends ThisType<T>, T extends Record<string, string | ((this: U) => string)>>(t: T) {
    // ...
}

const zoo = test({
    first_name: "John",
    last_name: "Doe",
    get_name() {
        // HOW TO GET `this.` working?
        return this.first_name + " " + this.last_name;
    }
})

https://www.typescriptlang.org/play/?ts=5.8.0-beta#code/GYVwdgxgLglg9mABFApgZygHgKqJQD1TABM1EAVACxjXIE8AHFTcgPgBoK9CUSyAlFBDgAnYpgwiYYAOadJ0mYgA+iABRqo1NAC5E2AJSIAvK0QLZB1q017yRgN4AoRK8QB6d4gCSURMTh0ZGpZNAB+JwBfJydhMAxEAC84OBNkdCg1ZzdEYBgRDAB9MABDAFsUPQAiACk4SjAq9hc3ABsSotKK6oARQKaW1xkUKGLylDVHQZzEERGQESQtGgA6PILRrpREAGpEKv3d4NX2zvGAbmnoyIMgA

earnest irisBOT
#

@near basalt Here's a shortened URL of your playground link! You can remove the full link from your message.

ciantic#0

Preview:```ts
function test<
U extends ThisType<T>,
T extends Record<
string,
string | ((this: U) => string)

(t: T) {
// It does things?
}

const zoo = test({
first_name: "John",
last_name: "Doe",
get_name() {
return this.first_name + " " + this.last_nam
...```

steel hill
#

What's the need for typing this? FYI, your code already works with just test<T>(t: T).

near basalt
#

@steel hill it gives errors:

#

so my This type is somehow wrong

steel hill
#

But why do you need it?

#

Simply test<T>(t: T) already works.

near basalt
#

but I want to have record of strings or functions that return a string (while using this)

#

test<T>(t: T) is too wide it allows numbers, and weird functions

steel hill
#
test<T extends Record<string, string | (() => string)>>(t: T)
near basalt
#

well, damned, that works! Thanks

#

somehow I thought I have to type this

#

.close

#

.resolve

#

/resolve

#

!resolve

#

@steel hill it somehow fails if done like this:

#

function test<T extends Record<string, string | (() => string)>>(t: T)
{

}

const zoo = test({
    first_name: "John",
    last_name: "Doe",
    get_name() {
        return this.first_name;
    }
})
earnest irisBOT
#
ciantic#0

Preview:```ts
function test<
T extends Record<string, string | (() => string)>

(t: T) {}

const zoo = test({
first_name: "John",
last_name: "Doe",
get_name() {
return this.first_name
},
})```

candid shell
#

seems like the inference order is not ideal in this case and TS thinks this.first_name may be a () => string. you can fix it by annotating the return type of get_name

#

pretty weird though

steel hill
#

Yeah Vue's options API also has similar problems, that you have to explicitly annotate return types to help TS with it.