簡體   English   中英

我可以定義一個枚舉和函數的打字稿變量嗎?

[英]Can I define a typescript variable that is an enum and a function?

這是到目前為止的代碼:

function fr(this: any, value: number) {
  return Object.keys(this).find(k => this[k] === value);
}

type getEnumValue = (value: number) => string;
type myEnum = typeof enumVal;

enum enumVal {
  a = 1,
  b = 2
}

let EnumEval = fr.bind(enumVal) as getEnumValue | myEnum;
Object.assign(EnumEval, enumVal);

// Why are the casts required?
console.log((EnumEval as myEnum).a);
console.log((EnumEval as getEnumValue)(1));

console.log(EnumEval as myEnum.a);
console.log(EnumEval(1));

最后兩行出現 TS 錯誤,需要我進行轉換。 為什么?

操場

干得好:

let EnumEval = fr.bind(enumVal) as (((value:number) => string) & (typeof enumVal));

或者:

let EnumEval = fr.bind(enumVal) as (typeof fr & typeof enumVal);

作為枚舉函數的變量- 所以它應該是交集& ),而不是聯合|

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM