TypeScript:从构造函数推断参数值并将其用作 class 方法参数的类型检查
TypeScript: Infer parameter values from constructor and use it as type checking on class method's parameter
不确定这是否可行,但我正在寻找一种方法让 TypeScript 自动推断 class 构造函数的参数值,然后使用推断的值对 [ 的另一个参数进行类型检查=28=]方法。
例如:
class MyClass {
// aim: to infer the string values from the rest parameter param2
constructor(param1: number, ...param2: string[]) {
console.log(param1);
console.log(param2);
}
// param uses values inferred from param2
classMethod(param) {
console.log(param);
}
}
目的是允许 TypeScript 从 param2
推断值,然后将其应用到 classMethod
的 param
。例如:
const myClass = new MyClass( 0, 'a', 'b', 'c' );
myClass.classMethod('a') // shall be correct
myClass.classMethod('x') // TypeScript shall highlight this with red wavy line
我试过使用泛型,但最终对如何从扩展字符串数组的泛型 T
推断值感到困惑。例如:
class MyClass<T extends string[] = []> {
constructor(param1: number, ...param2: T) {
// things
}
// how do I infer the array values in T?
classMethod(param) {
console.log(param);
}
}
也许我仍然缺乏一些步骤来正确地从泛型中推断出值。这可能吗?提前致谢!
非常感谢 @jonrsharpe,这是我对通用部分的疏忽。我会将此问题标记为您的回答。
这是@jonrsharpe 写的正确答案:
class MyClass<T extends string> {
constructor(param1: number, ...param2: T[]) {
// things
}
classMethod(param: T) {
console.log(param);
}
}
const myClass = new MyClass( 0, 'a', 'b', 'c' );
myClass.classMethod('a') // correct
myClass.classMethod('x') // error
不确定这是否可行,但我正在寻找一种方法让 TypeScript 自动推断 class 构造函数的参数值,然后使用推断的值对 [ 的另一个参数进行类型检查=28=]方法。
例如:
class MyClass {
// aim: to infer the string values from the rest parameter param2
constructor(param1: number, ...param2: string[]) {
console.log(param1);
console.log(param2);
}
// param uses values inferred from param2
classMethod(param) {
console.log(param);
}
}
目的是允许 TypeScript 从 param2
推断值,然后将其应用到 classMethod
的 param
。例如:
const myClass = new MyClass( 0, 'a', 'b', 'c' );
myClass.classMethod('a') // shall be correct
myClass.classMethod('x') // TypeScript shall highlight this with red wavy line
我试过使用泛型,但最终对如何从扩展字符串数组的泛型 T
推断值感到困惑。例如:
class MyClass<T extends string[] = []> {
constructor(param1: number, ...param2: T) {
// things
}
// how do I infer the array values in T?
classMethod(param) {
console.log(param);
}
}
也许我仍然缺乏一些步骤来正确地从泛型中推断出值。这可能吗?提前致谢!
非常感谢 @jonrsharpe,这是我对通用部分的疏忽。我会将此问题标记为您的回答。
这是@jonrsharpe 写的正确答案:
class MyClass<T extends string> {
constructor(param1: number, ...param2: T[]) {
// things
}
classMethod(param: T) {
console.log(param);
}
}
const myClass = new MyClass( 0, 'a', 'b', 'c' );
myClass.classMethod('a') // correct
myClass.classMethod('x') // error