鑒于這種型別:
type AThingWithGenerics<A, B, C> = {
name: string;
someFunction: (id: number) => A;
anotherFunction: () => B;
loveSomeGenerics: (s: string) => { foo: C };
};
其中A、B和C是隨值變化的物件。例如:
const aThing: AThingWithGenerics<{ foo: string }, { foo: number, bar: string }, { bar: string }> = {
name: "a_thing",
someFunction: (id: number) => { return { foo: "bar" }; },
anotherFunction: () => { return { foo: 3, bar: "foo" } },
loveSomeGenerics: (s: string) => { return { foo: { bar: "In this case C is an object containing a string" s } }; },
}
const anotherThing: AThingWithGenerics<{ bar: number }, { aString: string }, { bar: "test" }> = {
name: "another_thing",
someFunction: (id: number) => { return { bar: id 1 }; },
anotherFunction: () => { return { aString: "test" } },
loveSomeGenerics: (s: string) => { return { foo: { bar: "test" } } },
}
可以創建一個特定的元組AThingWithGenerics:
type ASpecificPileOfThings = [typeof aThing, typeof anotherThing];
它也可能使串列AThingWithGenerics只要A,B和C不變化:
type APileOfTheSameThing<A, B, C> = [AThingWithGenerics<A, B, C>];
但我想補充的相關串列AThingWithGenerics來AThingWithGenerics,所以aThing可能包括[anotherThing]作為related。問題是A、B和Cinrelated會有所不同。
那么如何創建一個包含不同泛型的型別呢?這是我到目前為止:
type AThingWithGenericsII<A, B, C> = {
name: string;
someFunction: (id: number) => A;
anotherFunction: () => B;
loveSomeGenerics: (s: string) => { foo: C };
related: Array<AThingWithGenericsII<A,B,C>>
}
const anotherThingWithRelated: AThingWithGenericsII<{ bar: number }, { aString: string }, { bar: "test" }> = {
name: "another_thing",
someFunction: (id: number) => { return { bar: id 1 } },
anotherFunction: () => { return { aString: "test" } },
loveSomeGenerics: (s: string) => { return { foo: { bar: "test" } } },
related: []
}
const aThingWithRelated: AThingWithGenericsII<{foo: string, bar: string }, { property: string }, { nestedFoo: number }> = {
name: "a_thing_with_related",
someFunction: (id: number) => { return { foo: "This is a string", bar: "" } },
anotherFunction: () => { return { property: "bar" } },
loveSomeGenerics: (s: string) => { return { foo: { nestedFoo: 3.1 } } },
related: [anotherThingWithRelated]
}
這不會進行型別檢查,因為A、B和Cs 型別不統一。如何AThingWithGenericsII更改以便aThingWithRelated型別檢查?
打字稿游樂場鏈接。我確定這個關于遞回泛型的問題是相關的,但我無法讓它適用于我的案例。
uj5u.com熱心網友回復:
嘗試使用AThingWithGenerics您定義的第一個介面,但添加此介面后,您不需要其他介面:
type AThingWithGenerics<A = any, B = any, C = any> = {
name: string;
someFunction: (id: number) => A;
anotherFunction: () => B;
loveSomeGenerics: (s: string) => { foo: C };
// some things might not have relatives
related?: Array<AThingWithGenerics>
};
將 typeany與泛型定義一起使用將使 typescript 推斷特定實體中使用的泛型型別。我們這樣做是為了允許該related屬性使用最終將由打字稿推斷的任何泛型。
只是為了添加界面背后的情緒,我認為并非所有“事物”都會相關,這就是為什么它可能undefined是在ts您提供的鏈接上發現的初始錯誤。
游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326528.html
