簡體   English   中英

Typescript 定制型

[英]Typescript custom type

如果我在 typescript 中有這樣的接口

interface MyInterface {
  id: number;
  image: string;
  text: "one thing" | "another" | "anotherthing" | "anotherthing" 
}

如何使用管道分解出我的文本類型,以便我可以在程序中多次使用它作為類型? 看起來應該很簡單,但我不確定語法是什么

為了清楚起見,我希望能夠像這樣使用它

factoredOutType = "one thing" | "another" | "anotherthing" | "anotherthing" 

interface MyInterface1 {
  id: number;
  image: string;
  text: factoredOutType
}

interface MyInterface2 {
  name: factoredOutType
}

等等......我似乎無法找到這個問題的語法,因此感謝您的幫助。

我認為您只需要type關鍵字:

type factoredOutType = "one thing" | "another" | "anotherthing" | "anotherthing"

現在不在編譯器附近,所以無法真正檢查,但我認為可行

如果您的類型是相關/動態的,您可以使用模板文字格式化字符串文字類型。 例如

type stringTypes =  `${'hello' | 'world'}_id`;
const a: stringTypes = 'hello_id'; 

暫無
暫無

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

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