簡體   English   中英

Typescript:如何使類型是接口的鍵,但只有鍵是字符串

[英]Typescript: How to make a type that is the keys of an interface but only the keys that are strings

假設我有這個界面

interface MyInterface {
   val1: string
   val2: string
   val3: number
   val4: string
   val5: Date
}

我想創建一個類型,它是 MyInterface 的鍵,但只有鍵是字符串:

type myType = keyof MyInterface //where key === typeof 'string'
// myType: 'val1' | 'val2' | 'val4'

我怎么能做這樣的事情?

您可以使用映射類型僅保留特定鍵,然后對結果類型執行 keyof

type myType = keyof {
    [P in keyof MyInterface as MyInterface[P] extends string ? P: never]: any
}

游樂場鏈接

你也可以讓它通用


type KeyOfType<T, V> = keyof {
    [P in keyof T as T[P] extends V? P: never]: any
}

type myType = KeyOfType<MyInterface, string>
type myType2 = KeyOfType<MyInterface, number>

游樂場鏈接

映射類型的as子句允許我們操作鍵的名稱。 如果鍵被映射到never從結果類型中刪除鍵。 您可以在此PR中找到更多信息

暫無
暫無

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

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