gpt4 book ai didi

typescript - 除了函数之外,TypeScript 中是否有任何类型?

转载 作者:搜寻专家 更新时间:2023-10-30 20:35:25 25 4
gpt4 key购买 nike

我想表达的是,参数应该是一个对象或一个简单的值类型(数字、 bool 、字符串等),而不是一个函数。

如果我使用Object,编译器会让我分配一个函数。

var test: Object = () => "a";

如果我使用any,结果当然也是一样的。在这种情况下,是否有可以帮助我解决问题的类型或技巧?

我的基本目标是在使用 Knockout observables 时保证安全,这样我就不会忘记那些小括号来打开它们:)

最佳答案

新功能回答

2018 年 11 月添加 - 因为条件类型现在很流行!

条件类型为此提供了一种可能的解决方案,因为您可以创建一个 NotFunction 条件类型,如下所示:

type NotFunction<T> = T extends Function ? never : T;

工作原理如下:

const aFunction = (input: string) => input;
const anObject = { data: 'some data' };
const aString = 'data';

// Error function is not a never
const x: NotFunction<typeof aFunction> = aFunction;

// OK
const y: NotFunction<typeof anObject> = anObject;
const z: NotFunction<typeof aString> = aString;

唯一的缺点是您必须将变量放在语句的左侧和右侧 - 尽管如果您犯了如下错误也是安全的:

// Error - function is not a string
const x: NotFunction<typeof aString> = aFunction;

原始答案

您可以使用 typeof 提供运行时检查,虽然这不是编译时检查,但会捕获您忘记执行函数的那些实例:

function example(input: any) {
if (typeof input === 'function') {
alert('You passed a function!');
}
}

function someFunction() {
return 1;
}

// Okay
example({ name: 'Zoltán' });
example(1);
example('a string');
example(someFunction());

// Not okay
example(function () {});
example(someFunction);

为什么你不能真正做你想做的事?

你几乎可以,因为你可以使用重载来允许“多种类型之一”,例如:

class Example {
someMethod(input: number);
someMethod(input: string);
someMethod(input: boolean);
someMethod(input: any) {

}
}

问题来了:为了允许对象类型,您必须添加 someMethod(input: Object);someMethod(input: {}); 的重载签名。只要你这样做,函数就会被允许,因为函数继承自对象。

如果您可以将 object 缩小到不太通用的范围,您可以简单地为您想要允许的所有类型添加越来越多的重载(哎呀)。

关于typescript - 除了函数之外,TypeScript 中是否有任何类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24613955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com