基于属性值的TypeScript通用 [英] TypeScript generic base on property value
问题描述
我想要一个接口,其中泛型类型基于此接口中属性的值:
I want to have an interface where the generic type is based on the value of a property in this interface:
interface Book<T extends BookType> {
type: T,
location: Shelf<T>,
}
而不是使用以下内容定义通用类型:
Instead of using the following to define the generic type:
const book: Book<BookType.Technology>;
我想要
const book: Book<???>;
book.type = BookType.Technology;
然后,提示"位置""具有类型为 Shelf< BookType.Technology>
在TypeScript中可以吗?
Is this possible in TypeScript?
推荐答案
TypeScript并不真正支持制作空对象,然后在以后按您想要的方式分配属性.通常,这里的解决方法是使用类型断言强烈键入空对象...但是您不想自己写出完整的 Book< BookType.Technology>
类型,所以这不是一个好建议.您希望对 BookType.Technology
部分进行类型推断,但这将无法正常工作,因为编译器不知道 type
将为 BookType.Technology
直到下一行.而且类型缩小不会向后起作用.
TypeScript doesn't really support making empty objects and then assigning properties later the way you want to do it. Usually the workaround here is to use a type assertion to strongly type the empty object... but you don't want to write out the full type Book<BookType.Technology>
yourself, so that's not a good suggestion. You'd like type inference for the BookType.Technology
part, but that won't work because the compiler has no idea that type
will be BookType.Technology
until the next line. And type narrowing doesn't work backwards.
TypeScript中的最佳实践是在单个语句中创建一个强类型对象,而不是在多个语句中添加单个属性.这对于编译器来说很容易理解.如果可以的话,那么我建议您使用一个辅助函数,该函数将为您推断 Book< T>
中的 T
.像这样:
Best practice in TypeScript is to make a strongly-typed object in a single statement instead of adding individual properties in multiple statements. This is a lot easier for the compiler to understand. If that's okay, then I'd suggest using a helper function which will infer the T
in Book<T>
for you. Like this:
const asBook = <T extends BookType>(book: Book<T>) => book;
使用时:
asBook({
type: BookType.Technology,
location: ... // this is hinted as Shelf<BookType.Technology>
})
位置
的类型将根据需要作为 Shelf< BookType.Technology>
提示给您.
the type of location
will be hinted for you as Shelf<BookType.Technology>
as you wanted.
希望有所帮助;祝你好运!
Hope that helps; good luck!
这篇关于基于属性值的TypeScript通用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!