我有以下函数调用:
this.get('barcode').scan();
Run Code Online (Sandbox Code Playgroud)
是否可以通过函数参数的值确定返回类型的方式来定义get函数.在我的情况下,'get'返回Barcode类,如果使用'barcode'调用,则返回Mqtt类,如果使用'mqtt'调用.
在 typescipt 中,我需要一种方法,让函数在给定特定类型的参数的情况下返回与参数类型相关的类型的对象。
请参阅下面的示例。我需要一种方法来使 'const response = ...' 的类型更窄。
下面的示例用于将特定类型的请求链接到仅与给定请求相关的响应。例如,给定一个查找用户信息的请求,我们想要一个包含他们的姓名和年龄的响应。但是,当收到查找汽车信息的请求时,我们希望得到有关汽车品牌和里程信息的响应。我们只想对“用户”请求使用“用户”响应,对“汽车”使用类似的响应。
class RequestBase {
}
class ResponseBase {
}
interface IFindUserReq {
user_id :string
}
class FindUserRequest implements IFindUserReq {
user_id :string
constructor(user_id) {
this.user_id = user_id
}
}
interface IFindUserRes {
name :string
age :number
}
class FindUserResponse implements IFindUserRes {
name :string
age :number
constructor(name, age) {
this.name = name;
this.age = age;
}
}
interface IFindCarReq {
car_id :number
}
class FindCarRequest implements IFindCarReq {
car_id :number
constructor(car_id) …Run Code Online (Sandbox Code Playgroud) 是否可以根据参数返回函数的类型?
我看到了基于字符串文字类型参数的变量返回类型,但它使用了重载。在这里,我有 100 多种类型,所以我不想进行重载。
interface Registry {
A: number,
B: string,
C: boolean,
// ... 100 more types like this
}
function createType<T = Registry[typeof myType]>(myType: keyof Registry, value: any): T {
// do some magic
// ...
return value;
}
const a = createType('A', 2); // Expected type: number. Actual: error above
Run Code Online (Sandbox Code Playgroud)
我试图创建一个具有两个构造函数的类,并发现TypeScript不允许这样,但它允许重载构造函数,我试过它并得到一个错误:
构建:重载签名与功能实现不兼容.
我的代码:
interface IShoppingListItem {
name: string;
amount: number;
}
export class ShoppingListItem implements IShoppingListItem{
name: string;
amount: number;
constructor(item: IShoppingListItem);
constructor(name: string, amount: number) {
this.name = name;
this.amount = amount;
}
copy() {
//return new this.constructor(this);
}
}
Run Code Online (Sandbox Code Playgroud)
我有两个问题,第一个问题,为什么我不能重载构造函数,我想我做错了什么.
但我的第二个问题,以及更多的交互是,我知道我的构造函数获取可选值.我可以(不使用方法中的代码!),在我的构造函数上创建一个条件,可以验证两个给定值中的一个必须存在,而在签名引导中是可选的,如下所示:
constructor(item?: IShoppingListItem, name?: string, amount?: number) {
//make a condition that item or name and amount must exist
this.name = name;
this.amount = amount;
}
Run Code Online (Sandbox Code Playgroud)
谢谢.