簡體   English   中英

在泛型接口中推斷變量類型

[英]Infer variable type in generic interface

我有以下示例。

enum Foo {
    bar,
    baz
}

interface IBar {
    qux: number
}

interface IBaz {
    quux: string
}

type InterfaceType<T> = 
    T extends Foo.bar ? IBar :
    T extends Foo.baz ? IBaz : never;
    
interface ICorge<T> {
    foo: T
    attributes: InterfaceType<T>
}

const grault: Array<ICorge<unknown>> = [
    {
        foo: Foo.bar,
        attributes: {
            qux: 404
        }
    }, {
        foo: Foo.baz,
        attributes: {
            quux: "not found"
        }
    }   
]

我希望從foo的類型自動推斷出我的接口ICorge的類型。 有沒有辦法在 typescript 中正確地做到這一點?

編輯:對不起,我有| 做錯了。

做就是了:

const grault: Array<ICorge<Foo.bar> | ICorge<Foo.baz>> = [
    {
        foo: Foo.bar,
        attributes: {
            qux: 404
        }
    }, {
        foo: Foo.baz,
        attributes: {
            quux: "not found"
        }
    }   
]

看它的TS 游樂場

相當有類型的儀式。 更實用的類型解決方案:

interface IBar {
    foo: 'bar'
    attributes: {
      qux: number
    }
}

interface IBaz {
    foo: 'baz'
    attributes: {
      quux: string
    }
}

const grault: (IBar | IBaz)[] = [
    {
        foo: 'bar',
        attributes: {
            qux: 44
        }
    }, {
        foo: 'baz',
        attributes: {
            quux: "not found"
        }
    }   
]

TS游樂場

至少我強烈建議不要在生產代碼中使用enums ,除非絕對必要。

暫無
暫無

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

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