在下面的例子中,是否有可能使parse()
可用,只有当key
使用TypeScript传递?
// SOURCE CODE:
interface Input {
key?: string;
data: Record<string, string>;
}
interface Options {
parse: (x: string) => void;
}
type HelperFunc = (options: Options) => void;
const myFunc = (input: Input, helper: HelperFunc): void => {
// How to implement this such that if key is passed, only then make `parse()` available?
// CONSTRAINT: I don't want to make `parse()` an optional field because user will call
// it multiple times and I don't want them to do `parse?.()` all the time.
if (input.key) {
helper({ parse: (x) => `${x} parsed using ${input.key}` })
} else {
helper({}); // currently throws valid TypeScript error
}
// do something with input.data
};
// EXPECTED USAGE:
myFunc({
key: "my-key",
data: {
"someData": "someValue"
}
}, ({ parse }) => {
// No TypeScript errors
parse("parse this");
parse("parse that");
parse("parse this and that");
});
// mentioning parse should throw TypeScript error because key was not passed
myFunc({
data: {
"someData": "someValue"
}
}, ({ parse }) => {
/* either throw error here when calling or while de-structuring above */
parse("parse this");
});
我想知道这是否可能使用TypeScript。
可以通过重载myFunc
函数来实现。
首先声明将用于每个参数的两种类型的接口。第一个-没有键:
interface InputData {
data: Record<string, string>;
}
type EmptyHelperFunc = (options: {}) => void;
和所有数据都存在的:
type Input = {
key?: string;
} & InputData;
interface Options {
parse: (x: string) => void;
}
type HelperFunc = (options: Options) => void;
然后可以如下声明和使用重载类型:
type MyFuncOverload = {
(input: InputData, helper: EmptyHelperFunc): void
(input: Required<Input>, helper: HelperFunc): void
}
const myFunc: MyFuncOverload = (input: Input, helper: HelperFunc): void => {
操场上链接。