我想生成一個具有 RoutesPath 確切名稱的型別。
因此,目的是擁有一個具有這些值的型別:
// type RoutesPath --> 'institutions' | 'credentials' | 'token'
但是現在,我只能生成泛型型別“字串”(type RoutesPath --> string)。
那可能嗎?
type RoutesPath = typeof routes[number]['children'][number]['path']
const routes = [
{
path: '/:token',
component: PLayout,
children: [
{
path: 'institutions',
name: 'display_information',
component: InstitutionsView
},
{
path: 'credentials',
name: 'display_credentials',
component: CredentialsView
},
{
path: 'token',
name: 'display_token',
component: TokenView
}
]
}
]
uj5u.com熱心網友回復:
是的,使用“const 斷言”可以實作您的目標
// type RoutesPath --> 'institutions' | 'credentials' | 'token'
檢查這個:
type RoutesPath = typeof routes[number]["children"][number]["path"];
const routes = [
{
path: "/:token",
component: "x",
children: [
{
path: "institutions",
name: "display_information",
component: "x",
},
{
path: "credentials",
name: "display_credentials",
component: "x",
},
{
path: "token",
name: "display_token",
component: "x",
},
],
},
] as const;
原因 :
如果您不使用此斷言,TS 編譯器會將型別推斷為 "RoutesPath" 的字串,您可以執行 const 斷言并將其推斷為文字型別。
注意:如果您不希望所有都是文字型別或只讀屬性,您可以執行以下操作。
const example = {
align: "left" as const,
padding: 0,
};
因此,推斷型別將是:
type example = {
align : "left",
padding : number,
}
如果你像下面這樣使用它,一切都將被視為文字。
const example = {
align: "left",
padding: 0,
} as const;
推斷的型別將是:
type example = {
align : "left",
padding : 0,
}
希望對你有幫助????
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519890.html
標籤:打字稿仿制药
上一篇:無法使用介面創建通用有界類物件
