有没有办法将联合类型转换为交集类型:
type FunctionUnion = () => void | (p: string) => void
type FunctionIntersection = () => void & (p: string) => void
Run Code Online (Sandbox Code Playgroud)
我想应用转换FunctionUnion来获取FunctionIntersection
我很惊讶地发现 TypeScript 不会抱怨我做这样的事情:
type sth = { value: number, data: string } | { value: number, note: string };
const a: sth = { value: 7, data: 'test' };
const b: sth = { value: 7, note: 'hello' };
const c: sth = { value: 7, data: 'test', note: 'hello' };
Run Code Online (Sandbox Code Playgroud)
我想也许value被选为类型联合判别式或其他东西,因为我唯一能想出解释这一点的是,TypeScript 是否以某种方式number在这里理解1 | 2为例如的超集。
所以我改变value是value2在第二对象上:
type sth = { value: number, data: string } | { value2: number, note: …Run Code Online (Sandbox Code Playgroud) 是否可以检查给定类型是否为联合?
type IsUnion<T> = ???
Run Code Online (Sandbox Code Playgroud)
为什么我需要这个:在我的代码中,我有唯一的情况,当一些收到的类型可以是一个联合.我用分配条件类型处理它.但是,对于查看此代码的人来说,首先使用DCT的原因并不明显.所以我希望它明确如下:IsUnion<T> extends true ? T extends Foo ...
我做了几次尝试UnionToIntersection,没有结果.我也想出了这个:
type IsUnion<T, U extends T = T> =
T extends any ?
(U extends T ? false : true)
: never
Run Code Online (Sandbox Code Playgroud)
它给false了非工会,但由于某种原因它给boolean工会......我不知道为什么.我也infer从T 尝试过U,没有成功.
PS我的用例可能看起来像某人不完美/正确/好,但无论如何标题中的问题已经出现,我想知道它是否可能(我觉得它是,但我很难自己搞清楚).
我正在使用 Redux 和Normalizr在 TypeScript 中构建 React Native 应用程序。所以我会有规范化的状态。
我有四个接口:Emotion、Need和:PainDataPainReport
export interface Emotion {
name: string;
chosen: boolean;
rating: number;
}
export interface Need {
name: string;
rating: number;
}
export interface PainData {
note: string;
emotions: Emotion[];
needs: Need[];
date: Date;
}
export interface PainReport {
[date: string]: PainData
}
Run Code Online (Sandbox Code Playgroud)
现在我想创建一个不是数组的接口,而是一个允许多个 PainReport 的对象,如下所示(伪代码):
export interface PseudoPainReportsObject {
[date: string]: PainData,
[date: string]: PainData,
[date: string]: PainData,
// ... dynamically have as many as …Run Code Online (Sandbox Code Playgroud) typescript redux normalizr typescript-typings typescript-types
我希望定义一个type可以只有一个键的对象。
这是一个尝试:
type OneKey<K extends string> = Record<K, any>
Run Code Online (Sandbox Code Playgroud)
不幸的是,这并不完全有效,因为变量可以具有联合类型:
type OneKey<K extends string> = Record<K, any>
declare function create<
K extends string,
T extends OneKey<K>[K]
>(s: K): OneKey<K>
const a = "a";
const res = create(a);
// Good
const check: typeof res = { a: 1, b: 2 }
// ~~ Error, object may only specify known properties
declare const many: "a" | "b";
const res2 = create(many);
// **Bad**: I only want one key
const check2: …Run Code Online (Sandbox Code Playgroud)