我正在尝试创建一个可以拥有的界面
export interface MenuItem {
title: string;
component?: any;
click?: any;
icon: string;
}
Run Code Online (Sandbox Code Playgroud)
component或click设置说我有这种类型:
export interface Opts {
paths?: string | Array<string>,
path?: string | Array<string>
}
Run Code Online (Sandbox Code Playgroud)
我想告诉用户他们必须传递路径或路径,但没有必要通过它们.现在的问题是这个编译:
export const foo = (o: Opts) => {};
foo({});
Run Code Online (Sandbox Code Playgroud)
有谁知道允许2个或更多可选但至少1是TS的必要参数?
我正在尝试使用类型系统对特定模式进行建模,其中对象仅由一组可能属性中的单个属性组成。
换句话说,该类型将是部分类型,但只允许一个属性。
interface PossibleProperties {
cat?: AllPropsOfSameType;
dog?: AllPropsOfSameType;
cow?: AllPropsOfSameType;
}
interface ShouldBeExactlyOneOfPossibleProperties {
[P in keyof PossibleProperties]: AllPropsOfSameType; // Wupz, this allows for 0 or more...
}
Run Code Online (Sandbox Code Playgroud)
我见过需要至少一个属性的解决方案:
type AtLeastOne<T, U = {[K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U]
Run Code Online (Sandbox Code Playgroud)
但我需要类似AtMostOne<T, U = {[K in keyof T]: Pick<T, K> }>or 的东西ExactlyOne<T, U = {[K in keyof T]: Pick<T, K> }>,它可能是AtMostOneand的交集类型AtLeastOne
如果这可能的话有什么想法吗?
考虑我有以下类型:
type SomeType = {
propOne: any;
propTwo: any;
propThree: any;
}
Run Code Online (Sandbox Code Playgroud)
是propOne必需的,propTwo并且propThree是可选的,但至少其中之一是必需的。如何定义具有该约束的类型?
// The following code is my expectation
let someVar1: SomeType = { propOne: 1, propTwo: "two" } //Okay
let someVar2: SomeType = { propOne: 1, propThree: "three" } //Okay
let someVar3: SomeType = { propOne: 1, propTwo: "two", propThree: "three" } //Okay
let someVar4: SomeType = { propOne: 1 } //Not Okay
Run Code Online (Sandbox Code Playgroud) 假设我有一个打字稿界面:
\n\ninterface MyInputInterface {\n a: A | null\n b: B |\xc2\xa0null\n aString: string | null\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这就是我目前所拥有的:
\n\nconst hasOneNonNull = (input: MyInputInterface) => \n input.a !== null || input.b !== null ||\xc2\xa0input.aString !== null\nRun Code Online (Sandbox Code Playgroud)\n\n但这看起来很脆弱。每次添加新的接口成员时,我都必须记住更新检查。有没有一种方法可以遍历所有接口成员并检查其中至少一个不为空?
\n\n像这样的东西会更理想(getAllMembers是伪代码):
const hasOneNonNull = (input: MyInputInterface) => \n input.getAllMembers().find((elem: any) => any !== null) !== null\nRun Code Online (Sandbox Code Playgroud)\n 当您使用 时Partial<SomeType>,从技术上讲,一个空对象满足该类型检查。有办法排除吗?
interface MyType {
foo: string
bar: string
}
function someFunction(obj: Partial<MyType>) {
// whatever
}
someFunction({}) // ideally, I would like this should throw a type error
Run Code Online (Sandbox Code Playgroud)