在下面的類中,propsmethod和payload. 例如,如果方法等于,sendTransaction則有效負載必須是一個SendTransactionRequest類。
如何使用型別強制執行此操作?
export enum RequestMethod {
SendTransaction = 'sendTransaction',
RequestAccounts = 'requestAccounts',
Other = 'other',
// ...
}
interface RequestProps {
id: number;
method: RequestMethod;
payload: ???;
}
export class Request {
private constructor(props: RequestProps)
this.props = Object.freeze(props);
}
public getID(): number {
return this.props.id;
}
public getMethod(): RequestMethod {
return this.props.method;
}
public getPayload(): ??? {
return this.props.payload;
}
public static create(props: RequestProps): Request {
return new Request(props);
}
}
uj5u.com熱心網友回復:
type為此,您應該使用打字稿。
您必須強制執行一些有限的允許型別組合,如下所示:
type SendTransactionRequest = string;
type RequestAccountsRequest = number;
type RequestMethod = "SendTransaction" | "RequestAccounts" | "Other";
type RequestProps = {
id: number;
} & (
| {
method: "SendTransaction";
payload: SendTransactionRequest;
}
| {
method: "RequestAccounts";
payload: RequestAccountsRequest;
}
);
使用這種型別定義,所有人RequestProps都會有一個id,但只有某些允許的method和組合payload。
// valid
const m1: RequestProps = {
id: 0,
method: 'RequestAccounts',
payload: 0,
}
// valid
const m2: RequestProps = {
id: 0,
method: 'SendTransaction',
payload: '',
}
// error: Type 'string' is not assignable to type 'number'
const m3: RequestProps = {
id: 0,
method: 'RequestAccounts',
payload: '',
}
// error: Type 'number' is not assignable to type 'string'
const m4: RequestProps = {
id: 0,
method: 'SendTransaction',
payload: 0,
}
如果您然后鍵入Request類以獲得正確的回傳型別,則getPayload()需要使用泛型:
export class Request<Props extends RequestProps = RequestProps> {
props: Props;
private constructor(props: Props) {
this.props = Object.freeze(props);
}
public getID(): number {
return this.props.id;
}
public getMethod(): RequestMethod {
return this.props.method;
}
public getPayload(): Props["payload"] {
return this.props.payload;
}
public static create<Props extends RequestProps>(
props: Props
): Request<Props> {
return new Request(props);
}
}
const req = Request.create({
id: 0,
method: "SendTransaction",
payload: "",
});
const payload = req.getPayload() // string
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450793.html
標籤:打字稿
上一篇:如何在TypeScript中獲取拾取屬性的型別而不是超型別的子集?
下一篇:一旦反應狀態為空,觸發一些API
