[英]Extend all properties of Interface or Type to be potentially null
我有一個類型:
type Base = {
propA: number;
propB: string;
}
並需要將其轉換為:
type BaseWithNull = {
propA: number | null;
propB: string | null;
}
其中所有屬性都可能是 null。 (未定義您可以使用“部分”的地方)
是否可以以編程方式執行此操作? 我已經嘗試過這樣的映射類型:
type BaseWithNull = Base | {
[P in keyof BaseRemoteWeatherForecast]: null;
};
type BaseWithNull = Base & {
[P in keyof BaseRemoteWeatherForecast]: null;
};
but the first (union) results in a type where it's either an object with the Base type or an object with all null properties, while the second (intersection) results in all properties as "never" types since null and doesn't "overlap " 具有非空類型。
您幾乎可以通過映射類型嘗試獲得它。 但是您需要包含鍵值的原始類型,然后將其與null
聯合:
type WithNull<T> = {
[P in keyof T]: T[P] | null;
}
type BaseWithNull = WithNull<Base>;
declare const test: BaseWithNull;
const nullable_number = test.propA; // Has type number | null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.