簡體   English   中英

基於鍵的打字稿元組函數參數

[英]Typescript tuple function arguments based on key

我正在為基於元組的 api 編寫類型。 我試圖推斷這個元組中函數的參數。

為了簡單起見,我舉了一個小例子來說明我大致想要實現的目標。

type InitType = ['init', (arg: string) => void]
type DestroyType = ['destroy', (arg: number) => void]
type GetType = ['get', () => void]

type Expected = InitType | DestroyType | GetType

// Expecting arg to be of type string
const test: Expected = ['init', (arg) => {
    console.log(arg)
}]

// Expecting arg to be of type number?
const test1: Expected = ['destroy', (arg) => {
    console.log(arg)
}]

// This does get checked tho..
const test2: Expected = ['get', () => {
    console.log(arg)
}]

截至 2022 年 12 月,可區分的元組並集的自動補全功能不如可區分的對象並集。

與基於對象的聯合比較:

type InitType = {name: 'init', fn: (arg: string) => void}
type DestroyType = {name: 'destroy', fn: (arg: number) => void}
type GetType = {name: 'get', fn: () => void}

type Expected = InitType | DestroyType | GetType

// arg is string
const test: Expected = {name: 'init', fn: (arg) => {
    console.log(arg)
}}

// arg is number
const test1: Expected = {name: 'destroy', fn: (arg) => {
    console.log(arg)
}}

// arg is noit available
const test2: Expected = {name: 'get', fn: () => {
    console.log(arg) // Expected error
}}

有一個未解決的問題可以精確地解決您的場景更好地自動完成區分聯合作為元組 #31977

暫無
暫無

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

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