[英]How can I extend an interface and override a property's type?
I have a pretty complicated object with multiple properties that I'd like to extend and override a specific property.我有一个非常复杂的 object,它有多个属性,我想扩展和覆盖一个特定的属性。
interface ComplicatedObject {
propertyOne: string,
propertyTwo: null
}
interface MoreComplicatedObject extends ComplicatedObject {
propertyTwo: string
}
Essentially, objects with the type ComplicatedObject
are converted to the MoreComplicatedType
by assigning a string value to propertyTwo
.本质上,通过为propertyTwo
分配一个字符串值,将类型为ComplicatedObject
的对象转换为MoreComplicatedType
。 I'd like to avoid using a union type on propertyTwo
because all calls using propertyTwo
assume that it's a string, not a null value, so I'd rather not have to include type checks in every instance where I access propertyTwo
.我想避免在propertyTwo
上使用联合类型,因为所有使用propertyTwo
的调用都假定它是一个字符串,而不是 null 值,所以我不想在访问propertyTwo
的每个实例中都包含类型检查。
How can I extend an interface and override the type of an existing property?如何扩展接口并覆盖现有属性的类型?
You can override property type when extending an interface only if the type in the extending interface is compatible with original type of the property. 仅当扩展接口中的类型与属性的原始类型兼容时,才可以在扩展接口时覆盖属性类型。 Usual case is when you are overriding it with more restrictive type. 通常的情况是,当你用更严格的类型覆盖它时。
It means that you have to have foresight and declare original property with a type that will be compatible with all possible extensions. 这意味着您必须具有远见并使用与所有可能扩展兼容的类型声明原始属性。 In your case, you can use union type in ComplicatedObject
: 在您的情况下,您可以在ComplicatedObject
使用union类型:
interface ComplicatedObject {
propertyOne: string,
propertyTwo: null | string
}
interface MoreComplicatedObject extends ComplicatedObject {
propertyTwo: string
}
Or you can make CompicatedObject
generic as described in this answer . 或者您可以按照本答案中的描述制作CompicatedObject
泛型。
You can make use of Omit<T, K>
, which allows you to omit certain keys of a type.您可以使用Omit<T, K>
,它允许您省略某种类型的某些键。 You can then use &
to append the keys you want.然后你可以使用&
到 append 你想要的键。
type A = {a: string, b: string}
type B = Omit<A, 'b'> & {b: number}
Note that you can declare A
as an interface, Omit<T,K>
similarly works.请注意,您可以A
声明为接口, Omit<T,K>
的工作方式类似。
Using the type-fest
npm package, you can use the Merge
helper to overwrite/override any property on the original, however you like:使用type-fest
npm package,您可以使用Merge
helper 覆盖/覆盖原始属性上的任何属性,但是您喜欢:
import {Merge} from 'type-fest'
type ComplicatedObject = {
propertyOne: string,
propertyTwo: null
}
type MoreComplicatedObject = Merge<ComplicatedObject, {
propertyTwo: string
}>
This may work with interfaces too, but I've only used it with object types.这可能也适用于接口,但我只将它用于 object 类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.