使用typeof后定义泛型函数的泛型类型

时间:2020-05-25 11:12:30

标签: typescript typescript-generics

看下面的例子:

function test<T>(a: T[]) {return a};
type testReturnType = ReturnType<typeof test> // typescript infers type unknown[]

是否可以通过参数化T的通用类型testType来选择T? 我希望做类似的事情:

type testReturnType<A> = ReturnType<typeof test<A>>

打字稿会推断testReturnType<A>的类型为A[],因此我可以执行以下操作:

function anotherFunction(b: testReturnType<number>) {..}

这有可能吗?

1 个答案:

答案 0 :(得分:0)

是的,很遗憾,没有纯TypeScript的方法:(

但是您可以像这样解决您的问题:

use scopeguard::defer;
use std::io::Error;
use std::ptr;
use winapi::shared::minwindef::FALSE;
use winapi::um::winbase::{GlobalAlloc, GlobalFree, GlobalLock, GlobalUnlock, GMEM_MOVEABLE};
use winapi::um::winuser::{CloseClipboard, OpenClipboard, SetClipboardData, CF_UNICODETEXT};

fn copy_to_clipboard(text: &str) -> Result<(), Error> {
    // Needs to be UTF-16 encoded
    let mut text_utf16: Vec<u16> = text.encode_utf16().collect();
    // And zero-terminated before passing it into `SetClipboardData`
    text_utf16.push(0);
    // Allocate memory
    let hglob =
        unsafe { GlobalAlloc(GMEM_MOVEABLE, text_utf16.len() * std::mem::size_of::<u16>()) };
    if hglob == ptr::null_mut() {
        return Err(Error::last_os_error());
    }
    // Ensure cleanup on scope exit
    defer!(unsafe { GlobalFree(hglob) };);

    // Retrieve writeable pointer to memory
    let dst = unsafe { GlobalLock(hglob) };
    if dst == ptr::null_mut() {
        return Err(Error::last_os_error());
    }
    // Copy data
    unsafe { ptr::copy_nonoverlapping(text_utf16.as_ptr(), dst as _, text_utf16.len()) };
    // Release writeable pointer
    unsafe { GlobalUnlock(hglob) };

    // Everything is set up now, let's open the clipboard
    let success = unsafe { OpenClipboard(ptr::null_mut()) } != FALSE;
    if !success {
        return Err(Error::last_os_error());
    }
    // Ensure cleanup on scope exit
    defer!(unsafe { CloseClipboard() };);
    // And apply data
    let success = unsafe { SetClipboardData(CF_UNICODETEXT, hglob) } != ptr::null_mut();
    if !success {
        return Err(Error::last_os_error());
    }

    Ok(())
}

fn main() {
    copy_to_clipboard("Hello, world!").expect("Failed to copy text to clipboard.");
}

然后,您可以尝试使用return Scaffold( body: SafeArea( child: SingleChildScrollView( child: Stack( children: <Widget>[ Column( children: <Widget>[ Container( height: 180, width: double.infinity, child: new Image.asset( 'assets/images/image.jpg', width: double.infinity, fit: BoxFit.fitWidth, ), ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Container( height: 110, width: 40, child: ListView.builder( shrinkWrap: true, itemCount: 10, scrollDirection: Axis.horizontal, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(10.0), child: Container( width: 100, height: 100, color: Colors.yellow, ), ); }, ), ), ], ), ), ], ), Padding( padding: EdgeInsets.only(left: 30, right: 30, top: 150), child: TextField( decoration: InputDecoration( prefixIcon: Icon(Icons.search), enabledBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.orangeAccent[200], width: 4.0), borderRadius: const BorderRadius.all( const Radius.circular(30.0), ), ), ), ), ), ], ), ), ), ); 类型执行更愚蠢的操作,然后查看代码是否仍然有效:

// First let's create a type signature for the test function
type TestFunction<T> = (params: T[]) => T[];

// Then the function itself
function test<T>(a: T[]) {
  return a;
}

// At this point you could say okay, I will just always make sure that test()
// is of type TestFunction. OR: You can bind them together!
// Since you cannot 'assign' a type to a function in TypeScript
// and you can't have generic const either you have to use a little trick:
const assertTest = <T>(): TestFunction<T> => test;

// The assertTest will just make sure that the signature of test()
// and the TestFunction type match. (you don't actually need to call it anywhere in your code)

// Then you can create your return type helper easily:
type TestReturnType<T> = ReturnType<TestFunction<T>>;

希望有帮助!