参数的默认值可以取决于打字稿中的另一个参数吗

时间:2020-06-26 17:13:20

标签: typescript

例如,我可以执行以下操作:

from tkinter import *
from PIL import Image, ImageTk
from playsound import playsound

def play():
    window = Toplevel()
    window.attributes('-fullscreen', True)
    img = ImageTk.PhotoImage(Image.open("pic.png"))
    label = Label(window, image=img).pack()
    playsound("song.mp3")
    
buttonWindow = Tk()
b = Button(buttonWindow, text="Press Button", command=play)
b.pack()

c是我要设置其默认值的参数,默认值取决于第一个参数。

我也可以相反吗? (我猜不是吗?)

const execute = (a, c = a.b) => {
// some logic
}

1 个答案:

答案 0 :(得分:1)

第一种形式没有问题。它甚至可以从c推断出a.b的类型。

const execute1 = (a: { b: number}, c = a.b) => {
    console.log(a, c)
}
execute1({ b: 123 }) // { b: 123 }, 123

但是,第二个无效。分配c时,尚未分配a。因此,编译器向您抱怨:

// Error: Parameter 'c' cannot reference identifier 'a' declared after it.(2373)
const execute2 = (c: number = a.b, a: { b: number }) => {
    console.log(a, c)
}

Typescript Playground with code