英文:
Extracting types of properties of generic interfaces still requires unnecessary generic type
问题
When I have an interface with a generic as such:
interface I1<S> {
a: string;
b: genericType<S>;
}
and try to extract the type of property a
using I1['a']
, TypeScript throws the following error:
TS2314: Generic type 'I1<S>' requires 1 type argument(s).
Should this not be fine since the extracted property type is not actually dependent on S
? Either I am failing to understand how TypeScript actually works or this should indeed be okay.
英文:
When I have an interface with a generic as such:
interface I1<S> {
a: string;
b: genericType<S>
}
and try to extract type of property a
using I1['a']
, typescript throws the following error:
TS2314: Generic type 'I1<S>' requires 1 type argument(s).
Should this not be fine since the extracted property type is not actually dependent on <S>
? Either I am failing to understand how Typescript actually works or this should indeed be okay.
答案1
得分: 2
属性 a
的类型与 S
无关,但你不能在 lookup 的一部分中省略类型参数。一些选项:
1.) 将 S
设置为 unknown
type T1 = I1<unknown>["a"] // string
2.) 在接口中为 S
声明默认值
interface I2<S = unknown> {
a: string;
b: S;
}
type T2 = I2["a"] // string
3.) 保持通用性
type T3<S> = I1<S>["a"] // T3<S> = string
// 在这种特殊情况下并不太有意义
英文:
Property a
type is not reliant on S
, but you cannot omit the type parameter as part of the lookup. Some options:
1.) Set S
to unknown
type T1 = I1<unknown>["a"] // string
2.) Declare a default for S
in the interface
interface I2<S = unknown> {
a: string;
b: S
}
type T2 = I2["a"] // string
3.) Keep it generic
type T3<S> = I1<S>["a"] // T3<S> = string
// doesn't make too much sense in this particular case
答案2
得分: 0
以下是翻译好的代码部分:
interface I1<S> {
a: string;
b: S;
}
// 在创建对象时需要指定S的类型:
// 请注意,下面的例子中,我为S泛型类型参数指定了string类型,但您可以选择任何您想要的类型作为“b”的类型。
const i1object: I1<string> = { a: "a", b: "b" };
const i1object2: I1<number> = { a: "a", b: 5 };
英文:
It should be:
interface I1<S> {
a: string;
b: S;
}
and you need to give the type of S when making the object:
notice I gave string type for the S generic type parameter below, but this can be any type you want the "b" to be.
const i1object: I1<string> = { a: "a", b: "b" };
const i1object2: I1<number> = { a: "a", b: 5 };
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论