簡體   English   中英

通過在 Typescript 接口中的屬性上聲明的 key 獲取泛型值的類型,並將其用作函數參數的類型

[英]Get type of generic's value by key declared on a property in Typescript interface and use it as the type of a function's parameter

我想在 typescript 接口上添加 function 簽名,其中一個參數將具有基於聲明的密鑰值的類型。

我嘗試了下面的方法,但它不起作用,因為value的類型是T中所有可能的類型。 相反,我想要聲明鍵的值

所以如果鍵“num”是一個數字,我希望 function 中的“value”參數是一個數字


type RowType = Record<string, any>

interface Row<T = RowType, K extends keyof T = keyof T> {
    key: K
    render: (value: T[K], row: T) => any
}

interface DumpRecord = {
    arr: string[], 
    num: number, 
    str: string
}

let row: Row<DumpRecord> = {
 key: 'arr',
 render: (value, row) => ... // value should be array, row should be DumpRecord
}

// or

let row: Row<DumpRecord> = {
 key: 'num',
 render: (value, row) => ... // value should be number
}


您需要在這里使用有區別的聯合

type RowType = Record<string, any>

interface Row<T = RowType, K extends keyof T = keyof T> {
    key: K
    render: (value: T[K], row: T) => any
}

interface DumpRecord {
    arr: string[],
    num: number,
    str: string
}
type Values<T> = T[keyof T]

type Union = Values<{
    [Prop in keyof DumpRecord]: Row<DumpRecord, Prop>
}>

const one: Union = {
    key: 'arr',
    render: (value, row) => {
        value // string[]

    }
}

const two: Union = {
    key: 'num',
    render: (value, row) => {
        value // number
    }
}

操場

您可以在這個問題和我的文章中找到更多示例

暫無
暫無

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

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