简体   繁体   English

TypeScript指定用于单个功能的类型

[英]TypeScript Specify Type For Individual Function Use

I have a function that returns multiple types (union type) but then I have another function later that uses the value returned from the first function but only accepts a single type. 我有一个返回多个类型(联合类型)的函数,但是后来我有了另一个函数,该函数使用第一个函数返回的值,但只接受一个类型。 Right now typescript is giving me an error saying that there is a type mismatch because the first function could potentially return something that would not be acceptable for the second function, but in the way that I am calling it I know it will not have a conflict. 现在,打字稿给我一个错误,指出类型不匹配,因为第一个函数可能返回第二个函数不可接受的内容,但以我所说的方式,我知道它不会发生冲突。 How can I inform typescript that the return value of the first method will work in the second? 如何告知打字稿第一种方法的返回值将在第二种方法中起作用?

Example: 例:

function returnNumberOrString (variable): string | number {
    if (variable === 'hello') return 'hello to you';
    if (variable === 123) return 456;
}

function onlyNumbers (number : number) {
    return number + 1;
}

let number = returnNumberOrString(123);

onlyNumbers(number); // This shows a warning because returnNumberOrString could possibly return a string

The accepted solution only hides the compiler error. 接受的解决方案仅隐藏编译器错误。 You will still be able to call onlyNumbers with a string even if you use Type Assertion to tell the compiler it is a number. 即使您使用Type Assertion告诉编译器它是一个数字,您仍将onlyNumbers使用字符串调用onlyNumbers If you perform the check I've written below, you won't ever pass anything but a number to your onlyNumbers function. 如果您执行我在下面写的检查,您将永远不会将数字传递给onlyNumbers函数。 This is a safer operation if you're doing anything that requires strictly numbers (as your function name implies) 如果您执行任何需要严格编号的操作(如您的函数名称所暗示的那样),这将是一种更安全的操作

function returnNumberOrString (variable): string | number {
    if (variable === 'hello') return 'hello to you';
    if (variable === 123) return 456;
}

function onlyNumbers (number : number) {
    return number + 1;
}

// Can pass string or number, will only ever get a number in val
let val = typeof returnNumberOrString(123) === "number" ? 456 : -1; // I used -1, you can use any value to mean "error" though.

console.log(val); // 456
console.log(onlyNumbers(val)); // 457

let val2 = typeof returnNumberOrString("hello") === "number" ? 456 : -1; 

console.log(val2); // -1
console.log(onlyNumbers(val2)); // 0 

This works for me: 这对我有用:

let n = returnNumberOrString(123);

onlyNumbers(<number>n);

As James notes, this hides the compiler error, but doesn't prevent the wrong value from being passed in, so you need to be very confident that you can guarantee by some other means what's being passed in. 正如James所指出的那样,这隐藏了编译器错误,但并不能防止传递错误的值,因此您必须非常确定可以通过其他方式保证所传递的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM