I've this function in typescript:
get_value(): T | undefined {
let TValue: T | undefined;
return TValue;
}
get_value() // result => undefined
The return can be type "T" and "undefined", in this case the above function always returns undefined. How can I return a string value?. For instance, the below function gives an error if I want to return a string:
export abstract class NVap<T> {
abstract get_value((): T | undefined;
}
export class Vap<T> extends NVap<T> {
get_value(): T | undefined {
let TAa: T | undefined;
//set a value string to the variable
TAa = "some str";
return TAa;
}
}
let task = new Vap();
task.get_value();
// result => result => error TS2322: Type '"some str"' is not assignable to type 'T | undefined'.
Thanks!
CodePudding user response:
If you want it to compile, make get_value() return T | string | undefined
export abstract class NVap<T> {
abstract get_value(): T | string | undefined;
}
export class Vap<T> extends NVap<T> {
get_value(): T | string | undefined {
let TAa: T | string | undefined;
TAa = "test";
return TAa;
}
}
let task = new Vap<string>();
task.get_value();
This approach doesn't make much sense to me, at least without more context. If you are not using the generic type T
and you assume that the return type will be a string
, why not making the return type of get_value() string | undefined
?
export class Vap<T> extends NVap<T> {
get_value(): string | undefined {
let TAa: string | undefined;
TAa = "test";
return TAa;
}
}
let taskBoolean = new Vap<boolean>();
console.log(taskBoolean.get_value());
let task = new Vap();
console.log(task.get_value());
CodePudding user response:
You need the specify which type has T
when you declare Vap(). Otherwise, T
will be interpreted as undefined as well.
Adding the type should do the work:
let task = new Vap<string>(); //If you want to retrieve a string
task.get_value(); // returns string | undefined
However, there is another problem in your code: you can't pass a string to a type T before declaring an object. This is because, when you specify a generic type, you have to define the type at "runtime". To make it works a possible adjustment is:
export interface NVap<T> {
get_value: () => T | undefined
}
export class Vap<T> implements NVap<T> {
value: T | undefined
constructor(value: T | undefined){
this.value=value
}
get_value(): T | undefined {
return this.value;
}
}
let task = new Vap<string>("Assign the string here");
task.get_value();
In this way, you define a pure class. However, if you need to update the value later, instead of passing it during construction, you can use a setter:
export class Vap2<T> implements NVap<T> {
value: T | undefined
set_value(value: T | undefined){
this.value=value;
}
get_value(): T | undefined {
return this.value;
}
}
let task2 = new Vap2<string>();
task2.set_value("Assign here");
task2.get_value();
I leave you this typescript playground to check the solutions I have just shown and to experiment with them.