如何使类型推断适用于 TypeScript 泛型方法

问题描述 投票:0回答:1

我试图用 TypeScript 重写一些 C# 代码,但无济于事。 除非我直接提供基类,否则无法推断响应类型。

class CommandParameter {
  readonly value: string = "value";
}

class Command<T> {}

class SubCommand<T> extends Command<T> {}

class Client {
  execute<T>(command: Command<T>): T {
    return null as T;
  }
}
//TS2339: Property 'value' does not exist on type 'unknown'.
const valueError = new Client().execute(new SubCommand<CommandParameter>()).value; //<--error
const valueOk = new Client().execute(new Command<CommandParameter>()).value;

是否有可能使用 Typescript 实现所需的行为(为子类进行推理)?可能有任何类似的替代模式吗?

typescript generics type-inference
1个回答
0
投票

这是您应该可以使用的代码的更新版本:

class CommandParameter {
  readonly value: string = "value";
}


class CommandParameter {
  readonly value: string = "value";
}

class Command<T> {}

class SubCommand<T> extends Command<T> {}

class Client {
  execute(command: Command<CommandParameter>): CommandParameter {
    return new CommandParameter();
  }
}

const valueError = new Client().execute(new SubCommand<CommandParameter>()).value; // no error
const valueOk = new Client().execute(new Command<CommandParameter>()).value;


© www.soinside.com 2019 - 2024. All rights reserved.