[英]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"
}
}
]
至少我強烈建議不要在生產代碼中使用enums
,除非絕對必要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.