i'm trying to use conditional types with 'this' Type in class context.
i summarized my issues, on those next examples:
type Foo<T> = T extends string ? T : never;
// 'Foo' conditional type don't pass with 'this' Type
class A {
public val: string = 'bar'
public getOtherVal(): Foo<this['val']> {
return 'baz' // error: Type 'string' is not assignable to type 'Foo<this["val"]>'.
}
}
// 'Foo' conditional type pass with class Type (here 'B')
class B {
public val: string = 'bar'
public getOtherVal(): Foo<B['val']> {
return 'baz'
}
}
// Typing with 'this' Type and without the conditional Type pass
class C {
public val: string = 'bar'
public getOtherVal(): this['val'] {
return 'baz'
}
}
The examples on the typescript playground => here
I actually don't understand why the first one don't pass whit "this" type ? This type is really convenient when you have to define abstracts classes but this issue globally blocking its usage with Conditional types... maybe i miss something but i'm open to some insights to fix it or other practices ?
thx for your help !
+++ Edit +++ to be more accurate on the issue:
The main idea in my context is to use This type to not fix Class type, That allow to add some constraint on some abstract methods or property of class, depending on its implementations.
I illustrated the issue in an other example :
type Foo<T> = T extends string ? T : (number | boolean);
// Not pass with conditional type:
// Abstract declaration
abstract class A {
public abstract val: string | number | boolean
// function return a value depending of class property value.
public abstract getOtherVal(): Foo<this['val']>
}
// Implementation of A class
class Aa implements A {
public val: string = 'bar';
// Return type constraint by the type of val.
public getOtherVal() { // error: ...Type 'string' is not assignable to type 'Foo<this["val"]>'.
return 'baz'
}
}
// Pass without conditional type:
// Abstract declaration
abstract class B {
public abstract val: string | number | boolean
// function return a value depending of class property value.
public abstract getOtherVal(): this['val']
}
// Implementation of B class
class Bb implements B {
public val: string = 'bar';
// Return type constraint by the type of val.
public getOtherVal() {
return 'baz'
}
}
On Typescript playground => here