我不明白为什么泛型函数自动获取泛型类型,而不提供任何东西.
type T<G = Record<string, any>> = {
id: keyof G
label: string
somethingElse?: string
}
此函数返回一个具有特殊属性id
的对象,如果没有将source
属性传递给该对象,则该对象应该具有类型"random"
.如果传递source
,则返回的id
应为source
的类型
const element = <ID extends string = 'random'>({ source }: { source?: ID } = {}) =>
({
id: (source || 'random') as ID,
label: 'Element1',
}) as const satisfies T
// I don't want the return type to be "T", I want what it returns to satisfy "T".
// as you see I dont provide "somethingElse" key here, so I don't want it in the return type
type Data = { a: string; b: number }
这给出了我想要的确切错误,但仅当我使用变量时:
const el1 = element() // el1 gets type { readonly id: "random"; readonly label: "Element1"; }
const el2 = element({source: 'b'}) // el2 gets type { readonly id: "b"; readonly label: "Element1"; }
const el3 = element({source: 'else'}) // el3 gets type { readonly id: "else"; readonly label: "Element1"; }
const b: T<Data>[] = [el, el2, el3] // el1 and el3 invalid, el2 valid. It is all correct
但是为什么这是有效的,当我直接使用它没有变量?它应该抛出一个错误
const a: T<Data>[] = [element()]
// No generic or property is provided to it "element()",
// why the return type of "element()" is { readonly id: keyof Data; readonly label: "Element1"; } ??