簡體   English   中英

Typescript keyof type 根據鍵數變化

[英]Typescript keyof type change based on number of keys

我有一個公開接口的庫。 我正在使用keyof功能向函數參數添加類型。 默認情況下,接口為空。 用戶可以擴展這個接口(模塊擴充)

如果接口不包含任何鍵,有什么方法可以將類型更改為any嗎?

interface A {}

function test(a: keyof A) {}


test('anyType') // here it should be `any`

interface A {
  id: number;
  name: string;
}

function test(a: keyof A) {}


test('name') // here it should be `id | name`

如果A沒有屬性keyof A解析為never 因此,您可以在此處使用條件類型,例如:

function test(a: keyof A extends never ? any : keyof A) {}

游樂場鏈接

暫無
暫無

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

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